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

如何通过ID定位Mongoose文档并向指定子对象数组元素添加值

问题与解决方案

问题描述

我需要通过program的_id找到对应的文档,然后在它的exercices数组中找到指定exercice ID的子对象,再向该子对象内添加值。

我的数据模型如下:

{
    "_id": "6347c79dafed140716087cc4", // program _id
    "title": "program 1",
    "user": "6347c67215178526c1dd403c",
    "exercices": [
        {
            "exercice": "6347c72052a0812efb3e1070",
            "totalSet": 3,
            "rest": "2mn"
            // 要在这里添加值
        },
        {
            "exercice": "6347c72aa5a04e37a2bdcf71",
            "totalSet": 3,
            "rest": "2mn"
        },
    ],
    "frequency": "1 fois par semaine",
    "__v": 0
}

当前代码会直接往exercices数组新增对象,无法定位到指定ID的子对象进行添加:

const program = this.programModel.findByIdAndUpdate(
    '6347c79dafed140716087cc4',
    {$push: {"exercices": { title: 'test' }}}
)

解决方案

要实现需求,需使用MongoDB的数组定位器配合arrayFilters来精准匹配数组内的目标元素,再执行字段添加或数组push操作。

场景1:给子对象添加单个字段

如果是给目标子对象新增一个字段(比如title),用$set配合定位器:

const program = await this.programModel.findByIdAndUpdate(
    '6347c79dafed140716087cc4',
    { $set: { "exercices.$[elem].title": 'test' } },
    { 
        arrayFilters: [ { "elem.exercice": "6347c72052a0812efb3e1070" } ],
        new: true // 返回更新后的文档
    }
);

场景2:往子对象的数组字段中添加值

如果目标子对象有数组字段(比如新增logs数组并添加内容),用$push配合定位器:

const program = await this.programModel.findByIdAndUpdate(
    '6347c79dafed140716087cc4',
    { $push: { "exercices.$[elem].logs": { weight: 100, reps: 12 } } },
    { 
        arrayFilters: [ { "elem.exercice": "6347c72052a0812efb3e1070" } ],
        new: true
    }
);

核心说明

  • arrayFilters:定义数组元素的匹配规则,这里通过elem.exercice匹配目标ID,elem是自定义占位符。
  • "exercices.$[elem].xxx":通过$[elem]定位到符合条件的数组元素,直接操作其内部字段。
  • new: true:配置后返回更新完成的文档,默认返回更新前的旧文档。

内容的提问来源于stack exchange,提问作者jeyremd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:10:54