My NodeJS app is working with ReplicaSet of mongo. I want to client read data from secondary, so I set readPreference=secondary, but If secondary is down, NodeJS app cannot read data from mongo. With option secondaryPreferred, if no secondary is available, NodeJS can read data from primary instance. But if have no primary available, have only secondary available, I cannot start NodeJS app. It throw error failed to connect to server [xxxx] on first connect [Error: connect ECONNREFUSED xxx.xx.xx.xx:27017
How I can config mix between secondary
and secondaryPreferred
. I expect my NodeJS can start even have only one instance available, no care it's primary or secondary. When NodeJS running, if have one mongo instance down, it's auto read from other instance
CodePudding user response:
"if have no primary available" is not normal state of the replica. Let the election to happen, then start your app.
Primary is a mandatory member of a replica set. All writes are going to primary. When you connect to the replica-set the driver should know where to write to, even if you don't intend to write on application level.
Once connected, your application can survive temporary loss of primary and read from secondaries.
As a side note - consider adding an arbiter. 2 nodes replica set is a recipe for disaster.