1

How can I find room by ID and make sure that the room has the current player in it?

My mongodb has a document of rooms which has players and a player is a user.

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}
})

I want to find room where id === roomId and room has a player with user._id === userId

My query so far just finds one room by ID but I want to make sure that the room returned has the current user in as a player

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

1 Answer 1

2

You can use mongodb aggregation framework for this task.

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
}

This will give a result like this when the user found, you may need some transformation.

[
  {
    "_id": "1",
    "players": {
      "_id": "10",
      "user": "100"
    },
    "user": [
      {
        "_id": "100",
        "username": "user1"
      }
    ]
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.