为什么 MongoDB 不更新,除非我在 findOneAndUpdate 之后调用“.then res.json(...)”?

Why does MongoDB not update unless I call ".then res.json(...)" after findOneAndUpdate?

理解这里的问题。我正在做一个 MERN 设置网站,我正在更新数据库中的一个字段,如下所示:

router.post("/updateLogApprovementStatus", (req, res) => {
  User.findOneAndUpdate(
    { _id: req.body.userId },
    { $set: { log: req.body.newData } }
  ).then(user => res.json(user.log));
});

但是在用正确的数据重复调用 api 之后,我的数据字段没有更新。但是,当我这样做时:

router.post("/updateLogApprovementStatus", (req, res) => {
  User.findOneAndUpdate(
    { _id: req.body.userId },
    { $set: { log: req.body.newData } }
  ).then(user => res.json(user.log));
});

我的数据库更新得很好。我所做的只是添加一个 res.json(),它发生在更新之后,因为它在 "then" 语句中,这让我想知道它为什么会磨损。 我很确定我所做的只是添加 then res.json() 语句。关于为什么这使它起作用的任何澄清?

如果我对你的问题的理解正确,你应该这样处理:

User.findOneAndUpdate(
  { _id: req.body.userId },
  { $set: { log: req.body.newData } }
).exec();

exec 函数将 运行 查询,这样您就不必处理 promise 结果。

原因是:"The query executes if callback is passed else a Query object is returned."(在 returns 部分下方)

.then() 不是一个真正的承诺,它被猫鼬伪装但充当执行。

你可以看到它执行查询here

.exec() 来自 documentation“执行查询”和 returns 一个 Promise(真实的)

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. If you need a fully-fledged promise, use the .exec() function.