It is important how to handle your MongoDb connections in your app. Basically when you fail to close an connection and try to open it instantaneously, you probably encounter this error. It can be while retrieving data, running tests, creating sessions.

Error:Trying to open unclosed connection.

As the error says you are trying to open an unclosed connection with MongoDb. Few things to know before you start with Mongoose to avoid these type of errors:

  • Do not open a connection for each web request.
  • Open it and leave it open until you close/shutdown your app.
  • Use createConnection instead of mongoose.connect if needed to connect to several different databases

Mongoose connect sample


  • Use mongoose.createConnection to create a new connection instance if needed.
  • For long running applications if you see "connection closed" errors try enable keepAlive

mongoose.connect opens a pool of connections that concurrent requests can share. You shouldn’t be connecting and disconnecting on each request. Instead, connect during your application start up and disconnect during shutdown.

Mongoose response hooks

Sometimes when you are streaming huge data you may need to close connections after every request. For this you can use after response events/hooks.


Connect-mongo session store tips

connect-mongo module which is commonly used for session store takes the param <span class="s2">"auto_reconnect"</span><span class="o">:</span> <span class="kc">true</span>. This will be passed as constructor to MongoDb server as the auto_reconnect option.

When using mongoose with connect-mongo you need to initialize the session store after mongoose connects.

Sample set-up can be found here.

Use existing mongoose connection

Yes, instead of creating a new Db object, you can just reuse the db object already instantiated by mongoose!



Mocha Tests

You don’t have to open a new connection for each test, connect once at the top level of your test and re-use the connection