Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Trying to open unclosed connection

This is a simplified version of the problem, but basically I'm trying to open 2 mongodb connections with mongoose and it's giving me "Trying to open unclosed connection." error.

Code sample:

var db1 = require('mongoose');
db1.connect('my.db.ip.address', 'my-db');

var db2 = require('mongoose');
db2.connect('my.db.ip.address', 'my-db');

db2.connection.close();
db1.connection.close();

Any idea how to make it work?

like image 407
Ben Wong Avatar asked Mar 29 '13 22:03

Ben Wong


3 Answers

connect() opens the default connection to the db. Since you want two different connections, use createConnection().

API link: http://mongoosejs.com/docs/api.html#index_Mongoose-createConnection

like image 167
Raghuveer Avatar answered Oct 24 '22 14:10

Raghuveer


To add on Raghuveer answer :

I would also mention that instead of using mongoose directly (you are probably using it this way you end up on this post) :

require('mongoose').model(...);

You would use the returned connection :

var db = require('mongoose').connect('xxx', 'yyy');
db.model(...);
like image 27
Thierry Avatar answered Oct 24 '22 15:10

Thierry


I get this issue while running my tests.

This is what I did to solve it.

//- in my app.js file.
try {
    mongoose.connect('mongodb://localhost/userApi2'); //- starting a db connection
}catch(err) {
    mongoose.createConnection('mongodb://localhost/userApi2'); //- starting another db connection
}
like image 2
ArchNoob Avatar answered Oct 24 '22 13:10

ArchNoob