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

使用router.post()无法修改MongoDB数据库中的String类型字段

问题分析与解决方案

问题根源

  1. 类型不匹配:你的goalsSchema中types定义为[String]数组,但当前代码里goalToModify.types.push(goalInsert)是把req.body(一个对象)推入数组,mongoose会对不符合类型的数据做转换,最终导致存入空对象。
  2. 错误处理漏洞:代码中存在未定义变量err的分支(比如找不到目标goal时),会触发隐藏错误。
  3. 低效更新逻辑:先查询再保存的方式不仅繁琐,还容易出现数据状态不一致的问题。

修复步骤

方案1:修正现有代码,确保推入字符串

根据你在Postman中发送的请求体格式调整代码:

  • 如果直接发送纯字符串(比如"reading"),直接使用req.body;
  • 如果发送JSON对象(比如{"type": "reading"}),提取对应字段。
router.post("/:id/goals/:idgoal/edit", (req, res) => {
  const { id, idgoal } = req.params;
  // 根据请求体格式选择取值方式
  const newType = typeof req.body === "string" ? req.body : req.body.type;

  if (!newType) {
    return res.status(400).json({ error: "缺少要添加的类型字符串" });
  }

  User.findById(id)
    .then((user) => {
      if (!user) {
        return res.status(404).json({ error: "未找到用户" });
      }
      const goalToModify = user.goals.find(
        (goal) => goal._id.toString() === idgoal
      );
      if (!goalToModify) {
        return res.status(404).json({ error: "未找到目标记录" });
      }
      goalToModify.types.push(newType);
      user.markModified("goals");
      user.save()
        .then(() => res.status(200).json({ message: "类型添加成功" }))
        .catch((err) => res.status(500).json({ error: err.message }));
    })
    .catch((err) => res.status(500).json({ error: err.message }));
});

方案2:使用mongoose更新操作符(推荐)

直接通过findByIdAndUpdate+数组过滤器完成更新,避免查询-修改-保存的冗余步骤:

router.post("/:id/goals/:idgoal/edit", (req, res) => {
  const { id, idgoal } = req.params;
  const newType = typeof req.body === "string" ? req.body : req.body.type;

  if (!newType) {
    return res.status(400).json({ error: "缺少要添加的类型字符串" });
  }

  User.findByIdAndUpdate(
    id,
    { $push: { "goals.$[goal].types": newType } },
    { 
      arrayFilters: [{ "goal._id": idgoal }],
      new: true // 返回更新后的文档
    }
  )
  .then(updatedUser => {
    if (!updatedUser) {
      return res.status(404).json({ error: "未找到用户或目标记录" });
    }
    res.status(200).json({ message: "类型添加成功", user: updatedUser });
  })
  .catch(err => res.status(500).json({ error: err.message }));
});

Postman请求注意事项

  • 发送纯字符串时,确保请求体Content-Type为application/json,直接输入带双引号的字符串(比如"meditation");
  • 发送JSON对象时,请求体格式应为{"type": "meditation"},Content-Type保持application/json。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:35:24