Home > Mobile >  Mongoose find query on nested objects returns empty array
Mongoose find query on nested objects returns empty array

Time:10-24

With Mongoose, I would like to be able to get a list of trainings by exercise _id parameter.

My training collection looks like this :

[
  {
    "_id": "617420adb9a7d7e02d591416",
    "workout": {
      "exercises": [
        {
          "_id": "61742066b9a7d7e02d5913ea",
          "name": "Exercise 1"
        }
      ],
      "name": "Workout 1",
      "_id": "617420a1b9a7d7e02d591401"
    },
  },
  {
    "_id": "617420b5b9a7d7e02d59141f",
    "workout": {
      "exercises": [
        {
          "_id": "61742066b9a7d7e02d5913ea",
          "name": "Exercise 2"
        }
      ],
      "name": "Workout 2",
      "_id": "617420a1b9a7d7e02d591401"
    },
  },
  {
    "_id": "6174226830610e43b0f6a283",
    "workout": {
      "exercises": [
        {
          "_id": "6174225630610e43b0f6a267",
          "name": "Exercise 2"
        }
      ],
      "name": "Workout 3",
      "_id": "6174226030610e43b0f6a275"
    },
  }
]

Based on MongoDB documentation I tried something like this :

this.trainingModel.find({
      'workout.exercises._id': '61742066b9a7d7e02d5913ea',
    });

This code returns an empty array. I was expecting to have two trainings (the two first of collection).

I also did this :

this.trainingModel.find({
      'workout.exercises': { _id: '61742066b9a7d7e02d5913ea' },
    });

But I also get an empty array as response.

CodePudding user response:

I have just found the solution. As @turivishal said I had first to convert the string id to ObjectId. But then I also had to change the query like this :

    this.trainingModel.find({
      'workout.exercises._id': new Types.ObjectId('my_string_id'),
    });

CodePudding user response:

You could use the aggregation framework and do something like this:

db.trainings.aggregate([
  {
      $group: {
          _id: { trainingId: '$workout.exercises._id'}
      }
  }
])
  • Related