问题
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