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.

Initialization

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

[https://gist.github.com/pasupulaphani/9463004?file=mongostore_conn.js](https://gist.github.com/pasupulaphani/9463004?file=mongostore_conn.js)

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.

[https://gist.github.com/pasupulaphani/9463004?file=connect-mongo_session_store.js](https://gist.github.com/pasupulaphani/9463004?file=connect-mongo_session_store.js)

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!

[https://gist.github.com/pasupulaphani/9463004?file=connect-mongo_use_mongoose_conn1.js](https://gist.github.com/pasupulaphani/9463004?file=connect-mongo_use_mongoose_conn1.js)

[https://gist.github.com/pasupulaphani/9463004?file=connect-mongo_use_mongoose_conn2.js](https://gist.github.com/pasupulaphani/9463004?file=connect-mongo_use_mongoose_conn2.js)

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

[https://gist.github.com/pasupulaphani/9463004?file=mongoose_connet.js](https://gist.github.com/pasupulaphani/9463004?file=mongoose_connet.js)