1

Can anyone help me understand why after update is complete my promise is returning the original (pre-updated) object from Mongo?

To be clear Mongo is being updated, I can see that when I access the database directly (shell), but it seems like the update takes effect after dbModel is returned; which doesn't make sense.

updateOneEvent: function (req, res) {
    db.Event.findOneAndUpdate({
        _id: req.params.eventId,
        user: req.session.user._id
    }, req.body)
        .then(dbModel => res.json(dbModel))
        .catch(err => res.status(422).json(err));
}
Farnoosh
  • 187
  • 1
  • 8

1 Answers1

2

Pass {returnNewDocument: true} in your options and it will return the new document rather than returning the document before it was updated. https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

See Mongoose: findOneAndUpdate doesn't return updated document for more details

klhr
  • 3,300
  • 1
  • 11
  • 25
  • Thanks Willis! I guess it makes sense that the default is false, since I'll have access to the updated object in the front end. – Farnoosh Feb 23 '19 at 17:35
  • It makes sense, but it's definitely one of those defaults that trips up every single person who's ever done anything on mongo – klhr Feb 23 '19 at 17:44