Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose disconnect does not work

I was trying to disconnect the mongoose connection after finishing the database work, but seems it didn't work

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase'); 

var MyModel =  mongoose.model('MyModel', MySchema);

//do something here

mongoose.disconnect();

The first time everything works fine, but when run the code for the second time, i get the error "Trying to open unclosed connection". I also tried mongoose.connection.close(); and got the same result.

Could anyone please help me with this?

Thank you very much!

Gary

I think i figured this out.

In my code, i was trying to do something with my model with the database:

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase'); 

var MyModel =  mongoose.model('MyModel', MySchema);

MyModel.findOne({}, function () {...});

mongoose.disconnect();

See the problem? Due to Nodejs's non-blocking feature, the "disconnect" was executed before "findOne" was completed, so of course it didn't work!

The solution is to put the disconnect into the callback function:

MyModel.findOne({}, function () {
...
mongoose.disconnect();
});
like image 562
Gary Avatar asked Jan 11 '13 14:01

Gary


People also ask

Does Mongoose close connection automatically?

You do need to call mongoose. disconnect() to close the connection, but you also need to wait until all save calls have completed their async work (i.e. called their callback) before doing that.

How does Mongoose Connect work?

Mongoose will try to connect with the MongoClient internally and return the instance of mongoose. this is the internal process of "conn. openUri" function and mongoose will execute the function. you can also connect the mongoClient directly without using mongoose.

What is the difference between Mongoose connect and Mongoose createConnection?

connect() and mongoose. createConnection() , particularly in general what are the things to considered when using one over another. My understanding on the official documentation is that generally when there is only one connection mongoose. connect() is use, whereas if there is multiple instance of connection mongoose.

Does Mongoose connect return a promise?

You don't handle a Promise with a callback: mongoose call you're callback if provided, otherwise it return the Promise.


2 Answers

try like this:

var db = mongoose.connect('mongodb://localhost:27017/myDatabase'); 
MyModel.findOne({}, function () {
    // todo
    db.disconnect();
});
like image 105
lancerex Avatar answered Oct 02 '22 18:10

lancerex


var db = mongoose.createConnection('mongodb://localhost:27017/myDatabase'); 

MyModel.findOne({}, function () {

     // Processing to be done

     db.close();
});
like image 40
Abhilash Chelankara Avatar answered Oct 02 '22 18:10

Abhilash Chelankara