Home > Mobile >  Why do I get 0 results when searching for a document with a certain subdocument? (mongodb & mongoose
Why do I get 0 results when searching for a document with a certain subdocument? (mongodb & mongoose

Time:09-26

I am trying to get all the documents that have the user in their array of member subdocuments. I am using the aggregate framework but I always get 0 results.

Using the .find() method works fine, but using agregate the query does not work.

await this.groupModel
  .find({ 'members.user_id': userId })
  .limit(limit)
  .sort({ updatedAt: 'desc' })
  .lean()

Example of a 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
}

Query I am using

await this.groupModel
  .aggregate<GroupDocument>()
  .match({
     'members.user_id': userId
  })
  .addFields({
  members_count: { $size: '$members' },
})
// ===> Result: []

Variables:

userId: string

CodePudding user response:

The problem here is the query is matchin string and ObjectId.

You can parse your string to ObjectId using mongoose.Types.OjectId(userId) like this:

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