Gary
Gary

Reputation: 513

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();
});

Upvotes: 8

Views: 7282

Answers (2)

Abhilash Chelankara
Abhilash Chelankara

Reputation: 406

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

MyModel.findOne({}, function () {

     // Processing to be done

     db.close();
});

Upvotes: 3

lancerex
lancerex

Reputation: 1260

try like this:

var db = mongoose.connect('mongodb://localhost:27017/myDatabase'); 
MyModel.findOne({}, function () {
    // todo
    db.disconnect();
});

Upvotes: 6

Related Questions