Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findOneAndUpdate not working

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. }); 
like image 790
lostintranslation Avatar asked Feb 27 '13 21:02

lostintranslation


People also ask

What does findOneAndUpdate return mongoose?

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.

What is the difference between updateOne and findOneAndUpdate?

findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).

Is findOneAndUpdate Atomic?

According to these docs , single write transactions are atomic. So with findOneAndUpdate, this would indeed be atomic.

What is Upsert in mongoose?

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.


1 Answers

Turns out that the id I was searching for did not exist, hence the null return. Works as expected!

like image 103
lostintranslation Avatar answered Oct 02 '22 12:10

lostintranslation