【问题标题】:Querying a referenced document in MongoDB using Mongoose使用 Mongoose 在 MongoDB 中查询引用的文档
【发布时间】:2018-12-07 11:13:25
【问题描述】:

这是集合BlogPosts中的一个文档:

{
    _id: ObjectId("..."),
    post_title: "Hello World!",
    post_body: "",
    comments: [
        { user_id: ObjectId("123"), body: "nice post!" },
        { user_id: ObjectId("456"), body: "awesome!" },
    ]
}

我想显示带有用户名的 cmets,该名可在 Users 集合中的引用文档中找到:

{
    _id: ObjectId("123"),
    first_name: "Marion",
    last_name: "Smith",
    email_address: "marion@example.com",
    password: "..."
}

有没有办法检索BlogPosts 文档,同时从该引用数据中包含first_name

例如,我正在寻找这样的输出(每个评论都有一个名字):

{
    _id: ObjectId("..."),
    post_title: "Hello World!",
    post_body: "",
    comments: [
        { user_id: ObjectId("..."), first_name: "Marion",  body: "nice post!" },
        { user_id: ObjectId("..."), first_name: "Margaret", body: "awesome!" },
    ]
}

我正在使用猫鼬。

【问题讨论】:

  • 什么是mongodb版本?
  • @felipsmartins 我正在使用 MongoDB 4.0。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

你可以使用下面的聚合

db.collection.aggregate([
  { "$unwind": "$comments" },
  { "$lookup": {
    "from": "users",
    "let": { "userId": "$comments.user_id" },
    "pipeline": [{ "$match": { "$expr": { "$eq": ["$$userId", "$_id"] } } }],
    "as": "user"
  }},
  { "$addFields": {
    "comments.first_name": { "$arrayElemAt": ["$user.first_name", 0] }
  }},
  { "$group": {
    "_id": "$_id",
    "comments": { "$push": "$comments" },
    "post_title": { "$first": "$post_title" },
    "post_body": { "$first": "$post_body" }
  }}
])

【讨论】:

    【解决方案2】:

    我后来找到了一种更直接的方法,只使用Populate

    BlogPosts
        .findOne({_id: req.params.id})
        .populate('comments.user_id', ['first_name', 'last_name'])
        .then(post => console.log(post))
    

    在 BlogPosts 的架构中,应为 comments.user_id 字段定义 ref

    const User = require('./User.model.js');
    
    const blogPostSchema = new Schema({
        post_title: { type: String },
        post_body: { type: String },
        comments: [{
            user_id: {
                type: Schema.ObjectId,
                ref: 'User'  <-------- here
            }
        }]
    });
    
    const BlogPost = mongoose.model('BlogPost', blogPostSchema);
    
    module.exports = BlogPost;
    

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2020-10-04
      • 2023-03-21
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多