1

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.

1
  • try converting string id to objectid 'workout.exercises._id': mongoose.Types.ObjectId('61742066b9a7d7e02d5913ea'), Commented Oct 23, 2021 at 15:37

1 Answer 1

1

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'),
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.