Mongoose connection to replica set
We use this:
if(config.db.indexOf('replicaSet') > - 1) { dbOptions = { db: {native_parser: true}, replset: { auto_reconnect:false, poolSize: 10, socketOptions: { keepAlive: 1000, connectTimeoutMS: 30000 } }, server: { poolSize: 5, socketOptions: { keepAlive: 1000, connectTimeoutMS: 30000 } } };}var db = mongoose.connect(config.db, dbOptions);
where
config.db = 'mongodb://USER:PW@host1:port1,host2:port2/DBNAME?replicaSet=RSNAME'
Auto_reconnect is off as per https://team.goodeggs.com/reconnecting-to-mongodb-when-mongoose-connect-fails-at-startup-83ca8496ca02
I had trouble with this too. What I learned from the experience is:
The "server" block is only invoked when the connection URI contain a single non clustered connection (aka a single connection string).
The "replset" block is only invoked when the connection URL contains a list of comma separated connection strings (aka replication set).
var options = { db: { native_parser: true }, // This block gets run for a non replica set connection string (eg. localhost with a single DB) server: { poolSize: 5, reconnectTries: Number.MAX_VALUE, ssl: false, sslValidate: false, socketOptions: { keepAlive: 1000, connectTimeoutMS: 30000 } }, // This block gets run when the connection string indicates a replica set (comma seperated connections) replset: { auto_reconnect: false, poolSize: 10, connectWithNoPrimary: true, ssl: true, sslValidate: false, socketOptions: { keepAlive: 1000, connectTimeoutMS: 30000 } }};
This block worked on both localhost and the production env.Hope it helps.
Your connection string is probably invalid. You should provide URI for every replica set member:
"uri": "mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/admin?replicaSet=myRepl"
You should check replica set connection section in the Mongoose documentation.