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

通过Mongoose向MongoDB数组插入元素仅保存第一条如何解决

问题原因

你的代码中使用的对象解构语法错误,仅提取了exercise数组的第一个元素,剩余元素全部被丢弃。
你使用的解构写法:

const {
  name,
  exercise: [{ exerciseId, period }],
} = req.body;

上述写法中exercise: [{ exerciseId, period }]只会匹配exercise数组的第一项,仅提取第一项的exerciseId和period字段,后续数组元素不会被处理。后续实例化Mongoose模型时,你又把提取到的单个元素包裹为数组传入,最终就只有第一条数据被存入数据库。

解决方法

无需单独解构exercise数组内部的元素,直接传递完整数组即可,可参考修改后的代码:

exports.create = (req, res) => {
  const { name, exercise } = req.body;
  // 可选参数校验,避免非法入参
  if (!Array.isArray(exercise)) {
    return res.status(400).send({ message: "exercise参数必须为数组格式" });
  }
  const newExercise = new Exercise({
    name,
    exercise, // 直接传入完整的exercise数组
  });
  newExercise.save((err, data) => {
    if (err) {
      res.status(500).send({ message: err });
      return;
    }
    res.status(200).send({
      message: "Success",
    });
  });
};

额外优化建议

  • 你当前Schema中timestamp的默认值写为Date.now(),该写法会在Schema加载时就执行一次生成固定时间,所有新文档都会复用这个固定时间,正确写法是传入函数引用:
    timestamp: { type: Date, default: Date.now },
    
  • 传入的exerciseId需要为合法的ObjectId格式,否则会触发Mongoose的字段校验报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:06:03