Mongoose populate, execPopulate not working

Viewed 3509

I have a mongoose model of 'Department' and another one of 'Course'. A one to many relation. Saving department id under department field in course document. I want to query all the departments and populate all their courses in one request. Here is the code for course schema

const mongoose = require('mongoose')


const courseSchema = new mongoose.Schema(
{
name:{
        type: String,
        trim: true,
        required: true
    },
 department:{
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Department'
    }
module.exports = mongoose.model('Course', courseSchema)

Heres the code for Department

const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt = require('bcryptjs')
const departmentSchema = new mongoose.Schema({
 title:{
        type: String,
        required: true
    },
admin: {
        type: mongoose.Schema.Types.ObjectId,
        trim: true,
    }
departmentSchema.virtual('courses',{
    ref: 'Course',
    localField: '_id',
    foreignField: 'department'
})
const Department = mongoose.model(' Department',departmentSchema)

module.exports = Department

Here is the route for getting all the departments

router.get('/departments', async (req, res)=>{
    Department.find().populate('courses').exec(function (err, departments) {
        if (err) {
            res.status(500).send(err)
        }
        res.status(200).send(departments)
    })
})

this code returns just departments without populating the courses array.

1 Answers

So i found the solution on the mongoose documentation. Apparently 'virtuals are not included in toJSON() output by default. If you want populate virtuals to show up when using functions that rely on JSON.stringify(), like Express' res.json() function, set the virtuals: true option on your schema's toJSON options.' so I modified my department schema to look like this

const departmentSchema = new mongoose.Schema({

    title:{
        type: String,
        required: true
    },
    admin: {
        type: mongoose.Schema.Types.ObjectId,
        trim: true,
        ref: 'User'
    }

},{
    timestamps: true,
    toJSON: {virtuals: true}
})
Related