0

Using Express and MongoDB, how can I update a document, then get that updated document?

The following code will find the profile document with the given user.id, then remove the experience with the given exp_id from the experience array. However, it returns the original profile (including the removed experience), not the updated one.

let profile = await Profile.findOneAndUpdate(
    { user: req.user.id },
    { $pull: { experience: { _id: req.params.exp_id } } },
    { returnNewDocument: true }
)

console.log(profile); // logs the original profile, still incl the removed experience

What do I need to change for it to return the updated profile?

Docs: https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

Ben
  • 15,938
  • 19
  • 92
  • 138
  • This appears to be all about the option passed to `findOneAndUpdate`. Various versions of that option are mentioned in other questions, for example `{ returnOriginal: false }`. The official MongoDB documentation states to use `{ returnNewDocument: true }`. This does not work for me. The only option that works for me is `{ new: true }`. – Ben Jul 14 '19 at 07:36
  • For anyone else who runs into this issue, if you are using mongoose, you need to refer to the mongoose documentation (https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate), not the mongodb documentation (https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/). The option is different between the two. – Ben Jul 14 '19 at 07:40
  • If anyone wants to write this up as an answer, I'll be happy to accept it. – Ben Jul 14 '19 at 07:44
  • That is what duplicate answers shows – Ashh Jul 14 '19 at 07:53

0 Answers0