【发布时间】:2022-04-26 06:11:23
【问题描述】:
所以我想填充两个东西并在响应中返回它们,我想返回一个images 和author 的数组。但是,如果我排除 .populate() 方法,则响应不会返回任何内容,那么它会使用 ObjectId 正常返回。不确定是什么原因。我该如何调试这个,我做错了什么?
// 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
}
【问题讨论】:
标签: mongoose mongoose-schema mongoose-populate