我想在我的 MongoDB\Mongoose 项目中创建一个带有注释的项目。由于这是我使用 MongoDB 的第一个项目,我有一个奇怪的问题:
我需要一个这样的项目文档
var itemSchema = new mongoose.Schema({
name: String
});
我需要对这个项目的评论是这样的:
var commentSchema = new mongoose.Schema({
text: String,
itemId: {type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
});
而且我不想在我的项目文档中保留评论 ID,如下所示:
var itemSchema = new mongoose.Schema({
name: String,
comments: [ {type: mongoose.Schema.Types.ObjectId, ref: 'Comment' } ]
});
那么如果我只知道价值,我应该如何调用模型Item
来获取comments
这个项目的所有信息Item.name
?我可以populate()
在一个 mongoose 请求中做到这一点,还是我必须提出两个请求(第一个Item
是查找_id
,第二个是去Comments
哪里itemId == Item._id
?
或者也许我这样做完全错误?
您可以使用虚拟人口。
itemSchema.virtual('comments', {
ref: 'Comment', // The model to use
localField: '_id', // Find comments where `localField`
foreignField: 'itemId', // is equal to `foreignField`
});
然后如果你有文件 item
,你会做
item.populate('comments').execPopulate().then(() => {
console.log(item.comments);
});
我们使用execPopulate()是因为您只想填充评论。
如果你有模型 Item
,你会做
Item.findOne(...).populate('comments').exec((err, item) => {
console.log(item.comments);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句