Mongoose:选择引用另一个文档的文档

时间:2017-09-04 21:03:01

标签: mongoose mongoose-populate

我想在MongoDB \ Mongoose项目中制作带注释的项目。 由于这是我与MongoDB的第一个项目,我有一个奇怪的问题:

我需要像这样的物品文件

var commentSchema = new mongoose.Schema({
text: String,
itemId: {type: mongoose.Schema.Types.ObjectId, ref: 'Item' },
});

我需要对此项目发表评论,如下所示:

var itemSchema = new mongoose.Schema({
name: String,
comments: [ {type: mongoose.Schema.Types.ObjectId, ref: 'Comment' } ]
});

不希望在我的Item文档中保留评论ID,如下所示:

Item

那么,如果我只知道comments值,我该怎样调用模型Item.name来获取此项目的所有populate()?我是否可以在单个猫鼬请求中使用Item执行此操作,或者我必须发出两个请求(首先要_id查找Comments,第二个要获取itemId == Item._id其中{{1}} 1}}?

或许我这样做是完全错误的?

1 个答案:

答案 0 :(得分:1)

您可以使用virtual population

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);
});
相关问题