You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:18:03