问题描述
我这里有 2 个合集>>课程和作者 我需要以引用作者的方式准备我的课程架构,并且在发布请求时我只需要输入 id。我使用的是 @joi13 这是我到目前为止所做的。
课程架构
const mongoose = require('mongoose')
const Joi = require('joi')
Joi.objectId= require('joi-objectid')(Joi)
// schema
const courseSchema = new mongoose.Schema({
...
author: {
type: mongoose.Schema.Types.ObjectId,ref: 'Author'
}
})
// the model
const Course = mongoose.model('Courses',courseSchema)
// validation
const courseValidation = (course) => {
const schema = {
...
authorId: Joi.objectId().required()
}
return Joi.validate(course,schema)
}
课程路由器
const {Course,validate} = require('../models/course')
const express = require('express')
const router = express.Router()
const {Author} = require('../models/author')
// post
router.post('/',async (req,res) => {
const {error} = validate(req.body)
if (error) return res.status(400).send(error.details[0].message)
const title = await Course.findOne({title : req.body.title})
if (title) return res.status(400).send('That user exists')
const author = await Author.find()
if (!author) return res.status(404).send('No such Author')
let course = new Course({
...
author: {
_id: author._id,username: author.username
}
})
try {
course = await course.save()
res.send(course)
}
catch(er){
console.log(er)
}
})
解决方法
在行中,const author = await Author.find()
将返回作者数组
在以下几行创建课程时,您正在使用 author._id 这将是 undefined
,因此您必须使用 findOne(返回单个作者作为对象)查找特定作者,或者您必须使用索引像author[0]._id
let course = new Course({
...
author: {
_id: author._id,username: author.username
}
})