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

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]


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

mongodb://username:password@host1:port1,mongodb://username:password@host2:port2


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
mongoose.connect(config.db,{
server:{
    'auto_reconnect':true,
    socketOptions:{
    keepAlive:1
   }
  }
});
    
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + config.db);
runApp(); 
//now mongo / mongoose is set up, boot the app...
});

.......
function runApp () {

......

app.use(express.session({
secret: config.sessionSecret,
store: new MongoStore({
db: mongoose.connection.db, //simply proxy the same connection from mongoose
collection:'Sessions'
})
}));

.....
/** 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

m.

Topics: MongoDB, Mongoose, NodeJs, Express

About the author

Matt Bryson is an experienced systems engineer with over 15 years Development and Systems Operations experience.

Product Briefing

In this short product briefing, see how iDetailAid customers are simplifying the creation, update, localisation and upload of CLM content.


New Call-to-action

Subscribe to Email Updates

Recent Posts