【问题标题】:findByIdAndUpdate returns 200 response but does not updatefindByIdAndUpdate 返回 200 响应但不更新
【发布时间】:2019-03-28 03:00:34
【问题描述】:

通过 findAndUpdateById 发送 put 请求,该请求在邮递员中返回 200 响应 - 但数据未更新。

put 请求是

app.put("/api/report/update/:id", (req, res) => {
  Report.findByIdAndUpdate(
    req.params.id,
    req.body.data,
    { new: true },
    (err, report) => {
      if (err) return res.status(404).send({ message: err.message });
      return res.send({ message: "report updated!", report });
    }
  );
});

发送的数据的形状是

    report: {
            month: "",
            updateMajor: "",
            updateMinor: "",
            comments: {
              comment1: "",
              comment2: "",
              comment3: ""
            },
          }

返回的数据与发送的完全相同。

感谢您的帮助。

【问题讨论】:

  • console.log(req.body) 检查req.body 中的内容,它很可能不包含您所期望的内容。

标签: mongodb express mongoose


【解决方案1】:

您需要在更新查询中使用一些update 运算符,例如$set$unset$push 等。因为你没有使用任何你得到这种行为的人。

如果您只想设置要发送的值,请尝试将其与$set 一起使用。

试试这个:

  Report.findByIdAndUpdate(
    req.params.id,
    {$set : req.body.data } ,
    { new: true },
    (err, report) => {
      if (err) return res.status(404).send({ message: err.message });
      return res.send({ message: "report updated!", report });
    }
  );

注意:$set 会覆盖之前的值。

如果您需要其他内容,请阅读MongoDB update Operators Documentation中的详细信息

【讨论】:

  • 实际上使用 mongoose(实际上问题是)$set 是隐含的并自动添加到发送到 MongoDB 的实际语句中。您可以通过mongoose.set('debug', true) 看到这一点。所以不,这不是问题。
  • $set 工作了我还必须发送每个字段和值而不是 body.data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
相关资源
最近更新 更多