[英]How to filter mongo document based on nested object?
How can I find room by ID and make sure that the room has the current player in it?如何通过 ID 找到房间并确保房间中有当前玩家?
My mongodb has a document of rooms which has players and a player is a user.我的 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}
})
I want to find room where id === roomId and room has a player with user._id === userId我想找到 id === roomId 的房间,并且房间有一个带有 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到目前为止,我的查询仅通过 ID 找到一个房间,但我想确保返回的房间有当前用户作为玩家
RoomModel
.findOne({_id: roomId})
.populate({
path: 'players',
populate: {
path: 'user',
model: 'User',
select: ["_id", "username"]
}
})
You can use mongodb aggregation framework for this task.您可以为此任务使用 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
}
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"
}
]
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.