I have a mongodb replica set
with the following config:
- M1 primary
- M2 secondary
- M3 secondary
- M4 arbitrator
Here is my Express code to connect to db (I use mongoose
as the ODM):
const config = {
db: `mongodb://${process.env.DB_ADDRESS_1}/${process.env.DB_NAME},
${process.env.DB_ADDRESS_2}/${process.env.DB_NAME},
${process.env.DB_ADDRESS_3}/${process.env.DB_NAME}`,
dbOptions: {
server: {
socketOptions: {
keepAlive: 1
},
poolSize: 5,
readPreference: 'nearest'
},
replSet: {
rs_name: process.env.REPLICA_SET,
poolSize: 5,
readPreference: 'nearest',
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS: 0
}
},
db: {
w: 1,
numberOfRetries: 2
}
}
}
mongoose.connect(config.db, config.dbOptions, (error) => {
if (error) {
console.log('Error on connecting to th db: ', error)
console.log('\x1b[31m', '*** PLEASE CONNECT TO DATABASE BEFORE RUN SERVER', '\x1b[0m')
process.exit(1)
}
callback()
})
The app works as expected.
When M1 get down, either M2 or M3 get elected to be the primary
, BUT my express
app still CAN'T connect to the replica set
.
Is there any wrong in my config?