Search code examples
javascriptmongodbes6-promise

mongo is not returning my updated object with the promise


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));
}

Solution

  • 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