【问题标题】:Mongoose: select documents that have reference to another documentMongoose:选择引用另一个文档的文档
【发布时间】:2018-02-13 02:24:35
【问题描述】:

我想在我的 MongoDB\Mongoose 项目中创建一个带有评论的项目。 由于这是我的第一个 MongoDB 项目,所以我有一个奇怪的问题:

我需要这样的项目文档

var itemSchema = new mongoose.Schema({
name: String
});

我需要这个项目的 cmets,如下所示:

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

而且我不想在我的 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

或者也许我这样做完全错误?

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案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() 是因为您只想填充 cmets。

    如果你有 model Item,你会这样做

    Item.findOne(...).populate('comments').exec((err, item) => {
        console.log(item.comments);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 2016-12-14
      • 2014-11-15
      • 2014-01-25
      • 1970-01-01
      • 2015-08-21
      • 2015-10-31
      相关资源
      最近更新 更多