Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongooseError: Query was already executed

I updated Mongoose to the latest version (6.0.1) and now I'm getting this error whenever .findOne() is executed:

MongooseError: Query was already executed: Streams.findOne({ i: 6 })
    at model.Query._wrappedThunk [as _findOne] (C:\Users\honza\ZiggerTestMaster\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
    at C:\Users\honza\ZiggerTestMaster\node_modules\kareem\index.js:370:33
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
    at runNextTicks (node:internal/process/task_queues:65:3)
    at listOnTimeout (node:internal/timers:526:9)
    at processTimers (node:internal/timers:500:7) {
  originalStack: 'Error\n' +
    '    at model.Query._wrappedThunk [as _findOne] (C:\\Users\\honza\\ZiggerTestMaster\\node_modules\\mongoose\\lib\\helpers\\query\\wrapThunk.js:25:28)\n' +
    '    at C:\\Users\\honza\\ZiggerTestMaster\\node_modules\\kareem\\index.js:370:33\n' +
    '    at processTicksAndRejections (node:internal/process/task_queues:78:11)\n' +
    '    at runNextTicks (node:internal/process/task_queues:65:3)\n' +
    '    at listOnTimeout (node:internal/timers:526:9)\n' +
    '    at processTimers (node:internal/timers:500:7)'
}

My code is as follows:

var visitorData = Visitor.find({});
    
app.get("/retrieve", function(req,res){
    visitorData.exec(function (err,data) {
        if (err) {
            throw err;
        }
        res.render("retrieve", { title:"View Visitor Data", records: data});
     });
});

It executes properly the first time I open the route but, whenever I refresh it, it throws the above error. Has been happening since Mongoose got the latest version.

like image 893
Zige Private Avatar asked Aug 26 '21 21:08

Zige Private


1 Answers

Had the same issues, but the release notes on mongoose helped, I chained a .clone() method to the .find() method:

https://mongoosejs.com/docs/migrating_to_6.html#duplicate-query-execution

Mongoose no longer allows executing the same query object twice. If you do, you'll get a Query was already executed error. Executing the same query instance twice is typically indicative of mixing callbacks and promises, but if you need to execute the same query twice, you can call Query#clone() to clone the query and re-execute it.

So all you need to do is to add a .clone() method to the end of the mongoose method that needs to be called concurrently like below (I restructured your code a bit):

app.get("/retrieve", function (req, res) {
    Visitor.find({}, function (err, data) {
        if (!err) {
            res.render("retrieve", { title: "View Visitor Data", records: data });
        } else {
            throw err;
        }
    }).clone().catch(function(err){ console.log(err)})
});
like image 80
Avis Avatar answered Sep 16 '22 22:09

Avis