如何通过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"]
}
})
答案 0 :(得分:2)
您可以使用mongodb聚合框架执行此任务。
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"
}
]
}
]