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

守給你的承諾、 提交于 2021-01-29 07:03:21

问题


understanding questions here. I am doing a MERN setup website, and I was updating a field in my database like this:

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

But after doing repeated calls to the api with correct data, my data field wasn't updating. However, when I do this:

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

My database updates perfectly fine. All I did was adding a res.json(), which occurs after the update since it is in the "then" statement, which makes me wonder why it wored. I am pretty sure that all I did was adding the then res.json() statement. Any clarifications on why this made it work?


回答1:


Reason being : "The query executes if callback is passed else a Query object is returned." (bellow the returns section)

.then() isn't really a promise, it's disguised by mongoose but acts as an execution.

You can see it execute queries here

.exec() from the documentation "Executes the query" and returns a Promise (true one)

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.




回答2:


If I understand your issue correctly, you should go with something like this:

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

The exec function will run the query and this way you don't have to handle the promise result.



来源:https://stackoverflow.com/questions/55885732/why-does-mongodb-not-update-unless-i-call-then-res-json-after-findoneand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!