【问题标题】:How do I reference documents from other collection in express如何在 express 中引用其他集合中的文档
【发布时间】:2021-09-23 23:24:55
【问题描述】:

我这里有 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)
    }
})

错误

【问题讨论】:

    标签: node.js express mongoose mongoose-schema joi


    【解决方案1】:

    在线时,const author = await Author.find() 将返回作者数组

    在以下几行创建课程时,您正在使用 author._id 这将是undefined,因此您必须使用 findOne 查找特定作者(返回单个作者作为对象),或者您必须使用索引元素像 author[0]._id

    这样的作者
    let course = new Course({
            ...
            author: {
                _id: author._id,
                username: author.username
            }
        })
    

    【讨论】:

    • 如果您觉得答案对您有用,请点赞。谢谢!
    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2021-12-03
    • 2011-05-25
    • 2018-05-30
    相关资源
    最近更新 更多