Search code examples
node.jsexpressmongoosemongoose-schemajoi

How do I reference documents from other collection in express


I have 2 collections here >>course & author I need to prepare my course schema in such a way that it references the author and at the post request I only need to put the id.I am using @joi13 This is what I have done so far.

course schema

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)
}

the course router

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)
    }
})

The error enter image description here


Solution

  • At line, const author = await Author.find() will return array of authors

    while creating course at following lines of you are using author._id which will be undefined, So you have to find a specific Author using findOne (return a single author as object) or you have to use an indexed element of an author like author[0]._id

    let course = new Course({
            ...
            author: {
                _id: author._id,
                username: author.username
            }
        })