0

I have a nodejs app that connects to mongodb.

Mongodb allows replicaset client connection to provide a level of resilience.

e.g "mongodb://localhost:50000,localhost:50001/myproject?replicaSet=foo", the client first connects to localhost@50000 and if that dies it switches to localhost@50001.

This is fine but if when the application starts and if one of the two mongo is dead then the application dies - with can't connect error.

The only solution I can think is to reformat the url so it excludes the inactive instance, but would like to avoid this ...

Any ideas?

Thanks

Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
nick
  • 1,431
  • 2
  • 11
  • 9

2 Answers2

1

Replicaset works fine when do you have an odd number of servers, because MongoDB ReplicaSet work using election between nodes for define what server will be the "primary".

You can to add a new node in your ReplicaSet just for voting. It's called "ARBITER".

You can understand more about ReplicaSet Elections on this page https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-elections.

1

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

kevinadi
  • 13,365
  • 3
  • 33
  • 49