【问题标题】:how to populate with other fields in mongoose?如何填充猫鼬中的其他字段?
【发布时间】:2021-01-25 22:37:32
【问题描述】:

我的第一个收藏价值是:

集合 1:

{
   _id:"5f82f1618cfa6d290c6271a9",
   name:"mehdi"
}

第二个收集值是:

集合 2:

{
    _id:"5f82f1618cfa6d290c6271aa",
    fid:"5f82f1618cfa6d290c6271a9",
    family:"parastar"
}

如何根据 coll1 中的 _id 和 coll2 中的 fid 填充基数?

我想成为,结果是这样的:

{
   {
    _id:"5f82f1618cfa6d290c6271aa",
    fid:"5f82f1618cfa6d290c6271a9",
    family:"parastar"
   },
   name:"mehdi"
}

你有什么想法吗?

【问题讨论】:

    标签: mongodb mongoose mongoose-populate


    【解决方案1】:

    你必须这样使用$lookup

    db.coll1.aggregate([
      {
        $lookup: {
          from: "coll2",
          localField: "_id",
          foreignField: "fid",
          as: "collection"
        }
      }
    ])
    

    此查询使用您想要的数据创建一个名为 collection 的字段:

    [
      {
        "_id": "5f82f1618cfa6d290c6271a9",
        "collection": [
          {
            "_id": "5f82f1618cfa6d290c6271aa",
            "family": "parastar",
            "fid": "5f82f1618cfa6d290c6271a9"
          }
        ],
        "name": "mehdi"
      }
    ]
    

    例如here

    使用Mongoose也是一样,只是查询写成这样:

    var agg = await model.aggregate([
        {
          $lookup: {
            from: "coll2",
            localField: "_id",
            foreignField: "fid",
            as: "collection"
          }
        }
      ])
    console.log(agg)
    

    【讨论】:

    • 谢谢,但我不能使用聚合,因为我的集合在不同的数据库中:(
    • 这是一个非常重要的细节,因为不可能。然后检查这个answerJira ticket 也已打开,因此未解决。
    猜你喜欢
    • 2021-05-06
    • 2014-01-08
    • 2016-04-25
    • 2019-05-04
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2021-07-26
    • 2022-12-10
    相关资源
    最近更新 更多