Mongoose查询嵌套对象返回空数组,如何按exercise _id筛选训练列表
问题原因
- 你传入的查询值是字符串类型,但嵌套在数组中的
exercise._id默认存储为ObjectId类型,类型不匹配导致查询无结果。Mongoose仅会自动转换文档顶层的_id类型,嵌套层级的_id需要手动转换。 - 第二种写法是要求数组元素完全匹配你传入的对象(不能有额外字段),但你的
exercise还包含name字段,因此无法匹配。
正确实现代码
首先引入mongoose的类型工具,将字符串id转换为ObjectId后再查询:
const { Types } = require('mongoose'); // 该写法会返回所有包含对应id exercise的training文档 this.trainingModel.find({ 'workout.exercises._id': Types.ObjectId('61742066b9a7d7e02d5913ea') });
如果你只需要返回匹配的exercise条目,不需要同数组下其他exercise,可以加投影参数过滤:
const targetId = Types.ObjectId('61742066b9a7d7e02d5913ea'); this.trainingModel.find( { 'workout.exercises._id': targetId }, { 'workout.exercises': { $elemMatch: { _id: targetId } }, 'workout.name': 1 // 其他需要返回的字段可自行配置 } );
内容的提问来源于stack exchange,提问作者L. Baptiste
相关产品推荐
相关产品推荐

