我有两个模型:
对于这篇文章,我写了这个模型:
const mongoose = require('mongoose');
const {Schema} = mongoose;
const ArticlesSchema = new Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
available_quantity: { type: Number, required: true },
})
const Articles = mongoose.model('articles', ArticlesSchema, 'articles');
module.exports = Articles;
对于我写的顺序:
const mongoose = require('mongoose');
const {Schema} = mongoose;
const ArtIdSchema = new Schema({
article_id: {type: Schema.Types.ObjectId, ref: 'articles'},
qty: {type: Number}
});
const OrdersSchema = new Schema({
status: { type: String, required: true },
user: { type: Schema.Types.ObjectId, required: true },
articles: [ArtIdSchema]
})
const Orders = mongoose.model('orders', OrdersSchema, 'orders');
module.exports = Orders;
我需要用真实的文章填充“ article_id”,因此在我的api.js中,我这样写:
router.get('/orders/status/:status_id', (req, res, next) => {
Orders.find({status: req.params.status_id}, 'status, articles')
.populate('article_id')
.exec((err, data) => {
if (err) {
return res.status(422).json({
error: 'Your request could not be processed. Please try again.'
});
}
res.status(200).json({
data: data
});
});
});
但是它不起作用。我还尝试将.populate('article_id')
替换为.populate('articles')
,但无法正常工作。
我是猫鼬的新手,我不明白哪里出了问题。
非常感谢您的帮助。
答案 0 :(得分:0)
我是个白痴。我解决了这个问题:
.populate('article.article_id')