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.
If you are following old courses of Node JS, you will always get this error. Because at that time .populate() method was not returning Promise to chain .then() method with it, what we were doing is that we would chain .execPopulate() method along with .populate() to chain .then() method on it.
So in order to work with .populate() correctly, just remove .execPopulate() because mongoose is no longer using it.
req.user
.populate("cart.items.productId")
.then((user) => {
console.log(user);
const products = user.cart.items;
res.render("shop/cart", {
path: "/cart",
pageTitle: "Your Cart",
products: products,
});
})
.catch((err) => console.log(err));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With