As Rafael mentioned, a replica set needs an odd number of members to be able to function properly when some of the members are offline. There are more details in the Replica Set Elections docs page, but the most relevant is:
If a majority of the replica set is inaccessible or unavailable to the current primary, the primary will step down and become a secondary. The replica set cannot accept writes after this occurs, but remaining members can continue to serve read queries if such queries are configured to run on secondaries.
The node driver by default requires a Primary to be online to be able to connect to the replica set, and will output an error you observed when you try to connect to a replica set without a Primary.
This default behaviour can be changed by setting connectWithNoPrimary
to true
. However, to be able to do queries, you also should set the proper readPreference
setting (which also defaults to Primary). For example:
var MongoClient = require('mongodb').MongoClient
conn = MongoClient.connect('mongodb://localhost:27017,localhost:27018,localhost:27019/test',
{
replicaSet: 'replset',
connectWithNoPrimary: true,
readPreference: 'primaryPreferred'
}).catch(console.log)
More information about the connection options can be found in the Node Driver URI Connection Settings page