I'm having trouble fetching all documents that contain the user in their array of member subdocuments. I've tried using the aggregate framework, but it always returns 0 results.
Interestingly, when I use the .find()
method, it works perfectly fine. However, the query doesn't seem to work with aggregate.
await this.groupModel
.find({ 'members.user_id': userId })
.limit(limit)
.sort({ updatedAt: 'desc' })
.lean()
Here's an example document:
{
"_id": {
"$oid": "614e0ab5a828578b4b2ee137"
},
"last_message": null,
"nsfw": false,
"icon": null,
"description": "test.",
"name": "test",
"owner": {
"$oid": "613fbe66c4c1631c28ccfd5a"
},
"roles": [],
"members": [
{
"roles": [],
"avatar": "a",
"nickname": null,
"user_id": {
"$oid": "613fbe66c4c1631c28ccfd5a"
},
"_id": {
"$oid": "614e0ab5a828578b4b2ee139"
},
"updatedAt": {
"$date": "2021-09-24T17:28:21.524Z"
},
"createdAt": {
"$date": "2021-09-24T17:28:21.524Z"
}
}
],
"createdAt": {
"$date": "2021-09-24T17:28:21.500Z"
},
"updatedAt": {
"$date": "2021-09-24T17:28:21.524Z"
},
"__v": 0
}
This is the query I'm running:
await this.groupModel
.aggregate<GroupDocument>()
.match({
'members.user_id': userId
})
.addFields({
members_count: { $size: '$members' },
})
// ===> Result: []
Variables being used:
userId: string