connect-mongo module which is commonly used for session store for a MongoDb backend. This post is an extension for my previous post MongoDB/Mongoose connect best practices. In this post I would like to elaborate good practices in using session store.


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


If not this might lead to the below errors.

Error:Trying to open unclosed connection.

Error: Error setting TTL index on collection : sessions

Enable auto reconnect

It also 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. By setting this you can avoid the below error

Error: no open connections

Sample set-up can be found here.


Use existing Mongoose or Mongo native connection

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



Also make sure that <span class="nx">mongoose</span><span class="p">.</span><span class="nx">connection</span><span class="p">.</span>db is fully initialized before used for session store otherwise it fails with TTL for ‘sessions’ error.

Using connect events

It is common practice to start app initialization with connection open event. If you use ‘open’ or ‘connecting’ events, there is a good possibility that the connection might not be fully initialized by the time you use it for session store. Make sure that you use appropriate events like ‘connected’ before you use existing mongoose connection. If not you might encounter above errors. Below is from a sample from my other post