【问题标题】:MongoDB, populate nested object in arrayMongoDB,在数组中填充嵌套对象
【发布时间】:2021-05-23 03:37:27
【问题描述】:

我有一个问题... 我有这样的架构:

const chatSchema = new Schema({
[...]
  title: {
        type: String,
        required: true
    },
   message: [
    {
      content: {
        type: String,
        required: true
      },
      creator: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'User'
      }
    }
  ],
[...]
});

在我的 Node 后端,我怎样才能访问我的消息数组中的创建者实例?我不知道如何用 populate 编写查询...

谢谢大家! :-)

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

您要查找的查询是:

https://mongoplayground.net/p/2dpeZWsXR-V

db.booking.aggregate([
  {
    "$match": {
      id: "61fdfeef678791001880da25"
    }
  },
  {
    $unwind: "$cart"
  },
  {
    "$lookup": {
      "from": "products",
      "localField": "cart.product",
      "foreignField": "id",
      "as": "prod"
    }
  },
  {
    "$unwind": "$prod"
  },
  {
    "$project": {
      id: 1,
      status: 1,
      cart: [
        {
          id: "$cart.id",
          date: "$cart.date",
          timeSlots: "$cart.timeSlots",
          product: {
            id: "$prod.id",
            name: "$prod.name",
            
          }
        }
      ],
      
    }
  }
])

【讨论】:

    【解决方案2】:

    你可以这样使用

    Chats.find(query)
      .populate({ 
         path: 'message',
         populate: {
           path: 'creator'
         } 
      })
      .exec(function(err, docs) {});
    

    【讨论】:

      【解决方案3】:

      使用以下命令:

      ...在将 chatSchema 导入为可能的聊天之后

      module.exports.populateCreator = (req, res) => {
        chats.findOne({chatID})
          .populate({
            path: 'message',
            populate: {
              path: "creator"
            }
          })
          .then(chats => res.json(chats))
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-18
        • 2022-11-10
        • 1970-01-01
        • 2019-09-23
        • 2020-08-30
        • 2017-10-03
        • 1970-01-01
        • 1970-01-01
        • 2017-01-01
        相关资源
        最近更新 更多