【问题标题】:Why do I get 0 results when searching for a document with a certain subdocument? (mongodb & mongoose)为什么搜索带有某个子文档的文档时得到 0 个结果? (mongodb & 猫鼬)
【发布时间】: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


【解决方案1】:

这里的问题是查询匹配string 和ObjectId。

您可以像这样使用mongoose.Types.OjectId(userId) 将字符串解析为ObjectId:

await this.groupModel
  .aggregate<GroupDocument>()
  .match({
     'members.user_id': mongoose.Types.OjectId(userId)
  })
  .addFields({
  members_count: { $size: '$members' },
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2023-03-04
    相关资源
    最近更新 更多