【发布时间】:2021-11-17 23:55:12
【问题描述】:
我正在尝试获取在其成员子文档数组中包含用户的所有文档。我正在使用聚合框架,但我总是得到 0 个结果。
使用.find() 方法可以正常工作,但使用聚合查询不起作用。
await this.groupModel
.find({ 'members.user_id': userId })
.limit(limit)
.sort({ updatedAt: 'desc' })
.lean()
文档示例
{
"_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
}
我正在使用的查询
await this.groupModel
.aggregate<GroupDocument>()
.match({
'members.user_id': userId
})
.addFields({
members_count: { $size: '$members' },
})
// ===> Result: []
变量:
userId: string
【问题讨论】:
-
尝试将
userId解析为ObjectId。因为现在您的查询似乎正在尝试比较字符串和 ObjectId,这就是结果为空的原因。 -
谢谢,这就是问题所在。
-
好消息!我还添加了一个答案,以防它对某人有所帮助。
标签: typescript mongodb mongoose mongodb-query aggregation-framework