findByIdAndUpdate返回200响应,但不更新

时间:2019-03-28 03:00:35

标签: mongodb express mongoose

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

放置请求是

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: ""
            },
          }

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您需要在更新查询中使用诸如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

中的详细信息
相关问题