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?
Using mongoose.disconnect(fn):
I found this question typing the error message and despite my problem is a bit different I believe it could be useful for those using Hapi. More specifically Hapi + rest-hapi + mocha.
When running
mocha
with--watch
option I was facing both:OverwriteModelError
andError: Trying to open unclosed connection errors
.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) :
You would use the returned connection :
I had this problem doing unit test with
mocha
.The problem came when I added a second test because
beforeEach
is called twice.I've solved this with this code:
Hope it helps you!
You are attempting to open the default connection ( which is not yet closed ) a 2nd time.
do the following instead
I get this issue while running my tests.
This is what I did to solve it.
connect()
opens the default connection to the db. Since you want two different connections, usecreateConnection()
.API link: http://mongoosejs.com/docs/api.html#index_Mongoose-createConnection