I've the following documents in database: (each document is a room with members)
[
{
"id": "room1",
"members": [{
"id": "member1",
"acks": "XXX",
},{
"id": "member2",
"acks": "XXX",
},{
"id": "member3",
"acks": "XXX",
},{
"id": "member4",
"acks": "XXX",
}]
},
{
"id": "room2",
"members": [{
"id": "memberA",
"acks": "XXX",
},{
"id": "memberB",
"acks": "XXX",
},{
"id": "memberC",
"acks": "XXX",
},{
"id": "memberD",
"acks": "XXX",
},{
"id": "memberE",
"acks": "XXX",
},{
"id": "memberF",
"acks": "XXX",
}]
},
{
"id": "room3",
"members": [{
"id": "memberX",
"acks": "XXX",
},{
"id": "memberY",
"acks": "XXX",
},{
"id": "memberZ",
"acks": "XXX",
}]
}
]
Sending from frontend next data:
[{
"id": "room1"
"members": ["member1", "member2"]
},{
"id": "room2"
"members": ["memberA", "memberB", "memberC", "memberF"]
},{
"id": "room3"
"members": ["memberX", "memberY"]
}]
I want to check if all members match for each room and return an unique boolean as a response --> True if all match and False if is someone that doesn't match.
This data should return false:
[{
"id": "room1"
"members": ["memberA", "member2"] //Because memberA is not in room1
},{
"id": "room2"
"members": ["memberA", "memberB", "memberC", "memberF"]
},{
"id": "room3"
"members": ["memberX", "memberY"]
}]
Is it possible to achieve it with one query?
Thank you very much in advance.
CodePudding user response:
You can try a query,
- Prepare your query request from frontend request
// consider this is your request parameter
let request = [{
"id": "room1",
"members": ["member1", "member2"]
},{
"id": "room2",
"members": ["memberA", "memberB", "memberC", "memberF"]
},{
"id": "room3",
"members": ["memberX", "memberY"]
}];
// prepare query
let query = request.map((r) => {
return {
id: r.id,
members: r.members.map((m) => {
return { "members.id": m }
})
}
});
console.log(query)
- Try
countDocuments
function and get total count of rooms with request
async function hasRooms (query) {
let count = await Schema.countDocuments({ $or: query });
return (count === request.length);
}
- Use your function
console.log(await hasRooms(query));