I am trying to use 'findOneAndUpdate' in mongoose and the updated JS object I am sending is not getting saved to mongo. I do not get an error upon saving, but I do get back a null for the updated object. Any ideas what I might be doing wrong? This is example is trying to update the entire object as stored in mongo, i.e. overwrite the name object.
var query = {"_id": id}; var update = {name: {first: 'john', last: 'smith'}}; var options = {new: true}; People.findOneAndUpdate(query, update, options, function(err, person) { if (err) { console.log('got an error'); } // at this point person is null. });
By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).
According to these docs , single write transactions are atomic. So with findOneAndUpdate, this would indeed be atomic.
May 20, 2019. In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.
Turns out that the id I was searching for did not exist, hence the null return. Works as expected!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With