Error: Error setting TTL index on collection - Mongo, Express, Mongoose, Replica Sets

Posted by Matt Bryson on 24-Sep-2014 18:17:47
Find me on:

We recently converted a Mongo DB backed Node app from a single monogo instance to a Replica Set. Which threw up a few errors, heres what we did....

Firstly, the way that the mongoose docs say to enter replicate set servers is as follows


However, this didnt work for us, we had to specify the full url for each connection, like this;


Once we had that, we were getting the following error regarding Sessions, and MongoStore.

Error: Error setting TTL index on collection

And then once that we solved we had this

Error: Error setting TTL index on collection : Sessions <MongoError: not authorized for query on ******.system.indexes>


Which were solved with the following...

1) Wait until the connection to Mongo was made and then start express and create the session store / MonogStore.
2) Swap the npm package connect-mongo for connect-mongostore, which supports replica sets.

So our app.js was something like this...

var MongoStore = require('connect-mongostore')(express) 
//connect-mongostore, not connect-mongo
// connect to MongoDB
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + config.db);
//now mongo / mongoose is set up, boot the app...

function runApp () {


secret: config.sessionSecret,
store: new MongoStore({
db: mongoose.connection.db, //simply proxy the same connection from mongoose

/** start the Express server listening */
var server = http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));


And with that we were up and running with replica sets


Topics: MongoDB, Mongoose, NodeJs, Express