You need to enable JavaScript to run this app. Mongoose使用findOneAndUpdate的$push向指定section的lessons插入数据失败如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose使用findOneAndUpdate的$push向指定section的lessons插入数据失败如何解决

问题原因

你的写法缺少两个关键逻辑:

  • 查询条件没有包含对应section的_id匹配规则,MongoDB无法定位你要操作的具体子文档
  • 更新路径没有使用$数组定位符来指代匹配到的section索引位置

正确写法

首先提前拿到要操作的section的_id值,记为targetSectionId,修改代码如下:

const updatedCourse = await Course.findOneAndUpdate(
  // 查询条件:同时匹配课程slug和目标section的_id
  { 
    slug: courseSlug,
    "sections._id": targetSectionId 
  },
  {
    $push: {
      // $符号代表前面查询匹配到的sections数组中对应元素的索引
      "sections.$.lessons": { title, content, free_preview, video: videoKey }
    }
  },
  { new: true, useFindAndModify: false }
);

注意事项

  • 如果你的targetSectionId是字符串类型,需要先转换为Mongoose的ObjectId类型再传入查询条件,避免类型不匹配导致查询失败:
    const targetSectionId = mongoose.Types.ObjectId(你的section_id字符串);
    
  • 如果需要同时更新多个匹配的section,你需要使用arrayFilters配合$[]标识符实现,单条匹配的场景用上述写法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 14:30:00