I have user schema
and invitation schema
.
When user search for users I want to return array with object that have property invited
.
const InvitationSchema = new Schema<IInvitation>(
{
sender: {
type: Schema.Types.ObjectId,
ref: 'user'
},
receiver: {
type: Schema.Types.ObjectId,
ref: 'user'
}
}
)
const IUserSchema = new Schema<IUser>(
{
email: {
type: String,
},
invitedUsers: [
{
type: Schema.Types.ObjectId,
ref: 'user'
}
]
}
)
Scenario of my problem:
- There are 3 users with ids – userId1, userId2, userId3
- User1 sends invitation to User2.
So current db becomes:
user1:{
id:userId1,
invitedUsers:[userId2]
}
invitation1:{
id:someId,
sender:userId1,
receiver:userId2
}
- Here User1 make a user search request to the server and receive:
users:[
{
id:userId2,
invited:true
},
{
id:userId3,
invited:false
},
]
I also want to paginated users but its not target of the current problem.
I tried some variants with aggregation $addFields but nothing works. The other way to do 10 queries more as the users per page are 10. This is bad idea of course.
2
Answers
If you want to check if the
invitedUsers
array has some length, then return true, otherwise false, then this could be done with aggregateexplore aggregate here
This is a nice question. One option is to do it with
$lookup
:id
is included at theinvitedUsers
we got from the requesting user.See how it works on the playground example
You can also improve the performance by using the
$lookup
pipeline to bring only the part you need:See how it works on the playground example – lookup-pipeline