Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

mongodb - findOneAndUpdate does not update unless I call ".then()". Why?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...