Acy
Acy

Reputation: 659

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

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?

Upvotes: 0

Views: 80

Answers (2)

Victor Jozwicki
Victor Jozwicki

Reputation: 720

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.

Upvotes: 1

ShaiShai
ShaiShai

Reputation: 144

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.

Upvotes: 0

Related Questions