【问题标题】:How to filter mongo document based on nested object?如何根据嵌套对象过滤 mongo 文档?
【发布时间】:2020-07-17 13:52:34
【问题描述】:

如何通过 ID 找到房间并确保房间中有当前玩家?

我的 mongodb 有一个房间文档,里面有玩家,玩家是用户。

const RoomSchema = new Schema({
  players: [{ type: Schema.Types.ObjectId, ref: "Player" }]
})

const PlayerSchema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: "User" }
})

const UserSchema = new Schema({
  username: { type: String}
})

我想找到 id === roomId 的房间,并且房间有一个带有 user._id === userId 的玩家

到目前为止,我的查询仅通过 ID 找到一个房间,但我想确保返回的房间有当前用户作为玩家

RoomModel
  .findOne({_id: roomId})
  .populate({ 
    path: 'players',
    populate: {
      path: 'user',
      model: 'User',
      select: ["_id", "username"]
    }
  })

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以为此任务使用 mongodb 聚合框架。

    Playground

    const result = await RoomModel.aggregate([
      {
        $match: {
          _id: "1",  // match by room id
        },
      },
      {
        $lookup: {
          from: "players",   // must be physical collection name, check if different
          localField: "players",
          foreignField: "_id",
          as: "players",
        },
      },
      {
        $unwind: "$players",
      },
      {
        $match: {
          "players.user": "100", //match by user id
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "players.user",
          foreignField: "_id",
          as: "user"
        }
      }
    ]);
    
    if (result.length > 0) {
      console.log("found"); //todo: add your logic when found
    } else {
      console.log("not found"); //todo: add your logic when not found
    }
    

    这会在用户发现时给出这样的结果,你可能需要一些转换。

    [
      {
        "_id": "1",
        "players": {
          "_id": "10",
          "user": "100"
        },
        "user": [
          {
            "_id": "100",
            "username": "user1"
          }
        ]
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 2020-03-11
      • 2019-07-03
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多