Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I cannot for the life of me figure out why my call to findOneAndUpdate does not update anything unless I handle the returned promise with .then(). I don't care what the call returns so I don't bother to handle the promise.

This does not work:

MyModel.findOneAndUpdate({key: 'XXXXX'}, {$set: {status: 'complete'}})

This works:

MyModel.findOneAndUpdate({key: 'XXXXX'}, {$set: {status: 'complete'}}).then()

Appending a .then() at the end certainly doesn't hurt me in any way, but I am simply curious as to why the call doesn't work without it. Shouldn't it still execute the query?

This guys seems to be asking the same question, but as of yet it's still unresolved: Why does MongoDB not update unless I call ".then res.json(...)" after findOneAndUpdate?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

The reason being : "The query executes if callback is passed else a Query object is returned."

.then() executes the function as seen here

For example, the below code will execute 3 updateMany() calls, one because of the callback, and two because .then() is called twice.

const q = MyModel.updateMany({}, { isDeleted: true }, function() {
  console.log('Update 1');
});

q.then(() => console.log('Update 2'));
q.then(() => console.log('Update 3'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...