'Can't populate Mongoose schema on express route
So I want to populate two things and return them in the response, I want to return an array of images
and the author
. However the response returns nothing, if I exclude the .populate() methods then it returns fine with the ObjectId. Not sure what the cause is. How can I debug this, am I doing something wrong?
// Product Controller:
router.get('/:id', (req, res) => {
Product.findById(req.params.id)
.populate('author')
.populate(['images'])
.then(product => res.json({ success: true, product: product }))
.catch(err => res.status(404).json({ success: false, err: err }));
});
// Product Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
name: {
type: String,
required: true,
},
images: [{
type: Schema.Types.ObjectId,
ref: 'Image',
}],
author: {
type: Schema.Types.ObjectId,
ref: 'User',
}
});
module.exports = Product = mongoose.model('product', ProductSchema);
// Product document:
{
"_id" : ObjectId("620ab784cde3e34263a9a3d9"),
"images" : [ ObjectId("620ab784cde3e34263a9a3d6") ],
"name" : "testing",
"author" : ObjectId("5db8f65bb027c31ede3b64ae"),
"__v" : 0
}
Solution 1:[1]
You can populate an array of ObjectIds using the same syntax as a single ObjectId. In other words, removing the brakets around the .populate(['images'])
line should do the trick. Like so:
//From:
Product.findById(req.params.id)
.populate('author')
.populate(['images'])
//To:
Product.findById(req.params.id)
.populate('author')
.populate('images')
Also, in your model file, your model references have a cap in them but the populate doesn't. Change your model file to match this, if I recall correctly, Mongoose converts model names to lower case so the ref here may be looking for a model that doesn't exist. Like so:
//From:
const ProductSchema = new Schema({
name: {
type: String,
required: true,
},
images: [{
type: Schema.Types.ObjectId,
ref: 'Image',
}],
author: {
type: Schema.Types.ObjectId,
ref: 'User',
}
});
//To:
const ProductSchema = new Schema({
name: {
type: String,
required: true,
},
images: [{
type: Schema.Types.ObjectId,
ref: 'image',
}],
author: {
type: Schema.Types.ObjectId,
ref: 'user',
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |