首页 > 解决方案 > Mongoose 对嵌套对象的查找查询返回空数组

问题描述

使用猫鼬,我希望能够通过练习 _id 参数获取培训列表。

我的训练集如下所示:

[
  {
    "_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"
    },
  }
]

基于MongoDB 文档,我尝试了这样的方法:

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

此代码返回一个空数组。我期待有两个培训(两个第一次收集)。

我也这样做了:

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

但我也得到一个空数组作为响应。

标签: mongodbmongoose

解决方案


我刚刚找到了解决方案。正如@turivishal 所说,我必须首先将字符串 id 转换为 ObjectId。但后来我也不得不像这样更改查询:

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

推荐阅读