How to Fix ‘Query was already executed’ in Mongoose

How to Filter an Object by Key in JavaScript

Apr 21, 2022

Mongoose throws a ‘Query was already executed’ error when a given query is executed twice.
The most common explanation for this is you’re mixing await and callbacks.

await Model.updateMany({}, { $inc: { count: 1 } }, function(err) {  });


Model.updateMany({}, { $inc: { count: 1 } }, function(err) {  }).then(() => { ... });

The solution is to skip passing a callback.
You don’t need callbacks in Mongoose, because Mongoose supports promises and async/await.

await Model.updateMany({}, { $inc: { count: 1 } });

Model.updateMany({}, { $inc: { count: 1 } }).then(() => { ... });

But I want to execute a query twice twice

If you’re absolutely sure you want to execute the exact same query twice, you can use clone()

let query = Model.findOne();

await query;

await query;

await query.clone();

Want to become your team’s MongoDB expert? “Mastering Mongoose” distills 8 years of hard-earned
lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need
to know to build production-ready full-stack apps with Node.js and MongoDB in a few days.
Get your copy!

More Mongoose Tutorials

Source link

Leave a reply

Please enter your comment!
Please enter your name here