8

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();
});
Gary
  • 483
  • 2
  • 6
  • 17

2 Answers2

6

try like this:

var db = mongoose.connect('mongodb://localhost:27017/myDatabase'); 
MyModel.findOne({}, function () {
    // todo
    db.disconnect();
});
lancerex
  • 1,222
  • 14
  • 12
3
var db = mongoose.createConnection('mongodb://localhost:27017/myDatabase'); 

MyModel.findOne({}, function () {

     // Processing to be done

     db.close();
});
  • In general it's not okay to use answers to circumvent the minimum rep requirement for comments. However, in this case I think it was legitimate to add this as an answer, because *if* it's correct it may be a necessary part of the solution that hasn't been posted yet. – Adi Inbar Apr 19 '14 at 19:29
  • However, one important point to clarify: You say "I had to add a reply", but please note that Stack Overflow has a question-and-answer format, not a discussion thread format, and "answer" doesn't mean "reply"; it means you're actually providing an answer to the question. Please read the [About] page to get a better understanding of the site's format. – Adi Inbar Apr 19 '14 at 19:31