2017-09-04 99 views
0

文件我想打一个项目,在我的MongoDB \猫鼬项目注释。 因为这是我的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()做一个单一的猫鼬请求或者我得把两个请求(第一个拿到Item查找_id,第二个得到Comments哪里itemId == Item._id

或者,也许我这样做完全错误的方式?

回答

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); 
});