mongodb - 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' },
});
但我也得到一个空数组作为响应。
解决方案
我刚刚找到了解决方案。正如@turivishal 所说,我必须首先将字符串 id 转换为 ObjectId。但后来我也不得不像这样更改查询:
this.trainingModel.find({
'workout.exercises._id': new Types.ObjectId('my_string_id'),
});
推荐阅读
- python - 单击命令默认参数和/或选项
- javascript - 无法上传多个图像 djago - ajax
- php - 如何在使用 codeigniter 插入数据库之前检查重复条目
- python - “开发人员:检查编辑器令牌和范围”未显示在 VS Code 上
- python - 如何有效地从一串 id 中获取存储在数据框中的一串值?
- apache-spark - 有没有办法丢弃不适合 AWS Glue 中特定架构的行?
- hangfire - Hangfire Jobs 正在运行旧版本的代码?
- reactjs - 如何在 React + Typescript 中更正 type event.target.value?
- node.js - 如何在express nodejs中使用以https开头的url作为参数
- css - 在我的css代码中的冒号后面不加空格不是更好吗?