【问题标题】:How get all objects from an array of Id's in mongoose with express nodejs?如何使用express nodejs从mongoose中的Id数组中获取所有对象?
【发布时间】:2021-12-03 17:11:38
【问题描述】:

我正在开发一个聊天应用程序,我正在像这样将对话列表保存在数据库中;

对话合集:

{ 
   members: [ "123", "456" ]
   ...rest
}

和用户收藏:

{
   _id: ObjectId( "123" ), name: "anyone"
},
{
   _id: ObjectId( "456" ), name: "someone"
}

我希望结果是这样的:

{
   members: [
              {_id: ObjectId( "123" ), name: "anyone"},
              {_id: ObjectId( "456" ), name: someone"}
            ]
}

我知道带有查找的聚合是一种解救方法,但找不到如何从该成员的数组中获取所有 id 的方法,因为将来它可能是 20 到 30 个 id。如果它是一个简单的字段,那么我可以获取但使用数组,我不能。

我试过了

db.conversations.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "members",
      "foreignField": "_id",
      "as": "members_details"
    }
  }
])

但它返回 members_details: [ ]

【问题讨论】:

    标签: node.js mongodb express mongoose mongodb-query


    【解决方案1】:

    您可以使用以下查询来完成您想要的。您需要使用$lookup,因为您希望从与当前查询的集合不同的集合中收集数据。

    您可以查看live demo here

    这是更新后的live demo

    数据库

    db={
      "conversations": [
        {
          members: [
            123,
            456
          ]
        }
      ],
      "users": [
        {
          "_id": 123,
          "name": "foo"
        },
        {
          "_id": 456,
          "name": "bar"
        }
      ]
    }
    

    查询

    db.conversations.aggregate([
      {
        "$lookup": {
          "from": "users",
          "localField": "members",
          "foreignField": "_id",
          "as": "members"
        }
      },
      {
        $project: {
          _id: 0,
          members: 1
        }
      }
    ])
    

    结果

    [
      {
        "members": [
          {
            "_id": 123,
            "name": "foo"
          },
          {
            "_id": 456,
            "name": "bar"
          }
        ]
      }
    ]
    

    更新

    查看新的live demo here

    新查询

    db.conversations.aggregate([
      {
        $unwind: "$members"
      },
      {
        "$lookup": {
          "from": "users",
          "as": "membersFlat",
          "let": {
            memberObjectId: {
              "$toObjectId": "$members"
            }
          },
          pipeline: [
            {
              $match: {
                $expr: {
                  $eq: [
                    "$$memberObjectId",
                    "$_id"
                  ]
                }
              }
            }
          ]
        }
      },
      {
        $group: {
          _id: null,
          members: {
            $push: {
              "_id": {
                $first: "$membersFlat._id"
              },
              "name": {
                $first: "$membersFlat.name"
              }
            }
          }
        }
      },
      {
        $project: {
          _id: 0
        }
      }
    ])
    

    新结果

    [
      {
        "members": [
          {
            "_id": ObjectId("124578987898787845658574"),
            "name": "foo"
          },
          {
            "_id": ObjectId("124578986532124578986532"),
            "name": "bar"
          }
        ]
      }
    ]
    

    【讨论】:

    • 这不起作用,因为在用户集合中 _id 表示为 ObjectId 类型而不是字符串。已经尝试过这个解决方案不起作用。总之谢谢
    • 我已经更新了你的演示检查 - mongoplayground.net/p/bfZENqF8s3c DB 会是这样的
    • 我继续并再次更新到演示以展示如何使用 ObjectId。 mongoplayground.net/p/T4Cjf3-G9mq
    • 谢谢,@matt,但我不能将成员数组作为数组的 ObjectId,因为它来自前端并直接保存到数据库
    • 查看我的答案的更新。现场演示见这里mongoplayground.net/p/-P1IcxG4JZZ
    【解决方案2】:

    由于您的members id 是会话集合中的字符串,您可以将其转换为对象 id 并加入用户集合,

    • $addFields 更新members 数组
    • $map 迭代 members 数组的循环
    • $toObjectId将字符串对象id类型转换为对象id类型
    db.conversations.aggregate([
      {
        $addFields: {
          members: {
            $map: {
              input: "$members",
              in: {
                $toObjectId: "$$this"
              }
            }
          }
        }
      },
      {
        $lookup: {
          from: "users",
          localField: "members",
          foreignField: "_id",
          as: "members"
        }
      }
    ])
    

    Playground

    【讨论】:

      【解决方案3】:

      您可以像这样使用普通的.find():

      const members = [
          ObjectId('4ed3ede8844f0f351100000c'),
          ObjectId('4ed3f117a844e0471100000d'), 
          ObjectId('4ed3f18132f50c491100000e')
      ]
      
      const docs = await model.find({
          '_id': { $in: members }
      }).exec()
      

      【讨论】:

      • 我想查询对话集合并尝试获取用户对象。正常查找将如何工作?
      • 对不起,我误解了这个问题
      【解决方案4】:

      安装mongoose-autopopulate。在你的模型代码中


      import {Schema, model} from 'mongoose';
      
      const modelSchema = new Schema({
         ...
         chats: [{type: Schema.Types.ObjectId, ref: "Chat", autopopulate: true}]
      })
      
      modelSchema.plugin(require('mongoose-autopopulate'));
      ...
      

      【讨论】:

        猜你喜欢
        • 2022-07-27
        • 2016-01-23
        • 2021-07-27
        • 1970-01-01
        • 2016-10-05
        • 1970-01-01
        • 2018-05-25
        • 2018-09-10
        • 1970-01-01
        相关资源
        最近更新 更多