Mongoose:select 个文档引用了另一个文档

Mongoose: select documents that have reference to another document

我想在我的 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.name 值,我应该如何调用模型 Item 来获取该项目的所有 comments?我可以在单个 mongoose 请求中使用 populate() 执行此操作,还是我必须发出两个请求(首先获取 Item 以查找 _id,第二个获取 Comments 其中 itemId == Item._id ?

或者我的做法完全错误?

您可以使用 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);
});