38

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?

Ben Wong
  • 385
  • 1
  • 4
  • 5
  • 1
    @NilsH: use case: DB connections decided by config file using different sections for different environments (prod, staging, dev) to create loose coupling between the application and the environment it is running in. In dev all databases are on localhost so that it's easy to manage; in production databases are on separate machines with different replication settings, etc. – robbrit Jun 12 '13 at 16:10

7 Answers7

46

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

Raghuveer
  • 1,737
  • 20
  • 27
  • This doesn't work on mongolab creating multiple connection for 2 database will result to `MongoError: database names cannot contain the character '.'` in mongolab – jofftiquez Feb 27 '16 at 08:04
2

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(...);
Thierry
  • 339
  • 1
  • 8
2

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
}
ArchNoob
  • 3,946
  • 5
  • 32
  • 59
2

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:

const mongoose = require('mongoose');
describe('Your test suite', () => {
    beforeEach( () => {
        if (mongoose.connection.db) {
            return; // or done();
        } else {
            // connect to mongodb
    });

    describe('GET /some-path', () => {
       it('It should...', () => {

       });
    });

    describe('POST /some-path', () => {
       it('It should...', () => {

       });
    });
});

Hope it helps you!

saeta
  • 4,048
  • 2
  • 31
  • 48
0

You are attempting to open the default connection ( which is not yet closed ) a 2nd time.

do the following instead

var db = require('mongoose'); //note only one 'require' needed.
var connectionToDb1 = db.createConnection('my.db1.ip.address', 'my-db1');
var connectionToDb2 = db.createConnection('my.db2.ip.address', 'my-db2');
Edwin O.
  • 4,998
  • 41
  • 44
0

Using mongoose.disconnect(fn):

mongoose.disconnect(() => {

  // here it would be possible "reset" models to fix 
  // OverwriteModelError errors
  mongoose.models = {};

  // here comes your logic like registering Hapi plugins
  server.register(somePlugin, callback);
});

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 and Error: Trying to open unclosed connection errors.

Moacir Rosa
  • 146
  • 2
  • 9
0

Simple Solution -

 Use mongoose.createConnection() instead of  mongoose.connect()
    
    Its occurs because of version issue
Shashwat Gupta
  • 5,071
  • 41
  • 33