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.