user3019507
user3019507

Reputation: 11

MongoDB replica set write with node.js

I use mongodb native driver for node.js to connect to replica set of 3 nodes(PRIMARY and two SECONDARIES) as described here: http://mongodb.github.io/node-mongodb-native/2.0/api/MongoClient.html

 var MongoClient = require("mongodb").MongoClient;     

 var url = "mongodb://admin:pass@hostname:27017";
 var options = {
  db: {
    readPreference: 'primaryPreferred',
    slaveOk: true
  },
  replSet: {
    replicaSet: 'rs0'
  },
  server: {
    w: 1,
    autoReconnect: true
  };

 MongoClient.connect(url, options);

Note that slaveOk: true is not documented, without it I keep getting slaveOk is false error. I keep getting Potentially unhandled rejection [83] MongoError: not master on writes. Can you please help to connect to a replica set from node application? Maybe I shall specify all the servers for the connection? But it's said in docs that driver is smart enough to reconnect when PRIMARY changes.

Upvotes: 1

Views: 1390

Answers (1)

Philipp
Philipp

Reputation: 69703

In order to allow the client to switch between replica-set members as needed, you need to tell it that these alternative replica-set members exist. To do this, provide the URLs of all the replica-set members separated by comma.

var url = "mongodb://admin:pass@hostname1:27017,mongodb://admin:pass@hostname2:27017,mongodb://admin:pass@hostname3:27017,";

When you want to abstract the replica-set configuration from the application to have more flexibility, you can build a sharded cluster and have the application connect to the router. The router will then take care of forwarding the connection to an appropriate replica-set member

Upvotes: 2

Related Questions