Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js / MongoDB replica set array in javascript

Warning: I'm a novice programmer (more of sysadmin). We were given an node js application that's using MongoDB. From what I can tell, the mongo.js file is using mongojs and monq java classes. It was setup with only one MongoDB and I'm trying to setup a new HA environment to use a replica set. Here is what they provided:

var mongojs = require('mongojs');
var monq = require('monq');
var dbName = 'exampledb';
var db = mongojs(dbName, ['collections']);
var client = monq('mongodb://127.0.0.1/exampledb', { w: 1 });

exports.db = db;
exports.ObjectId = mongojs.ObjectId;
exports.monqClient = client;

Now for a replica set, according to this article, I need to make the following change:

var db = mongojs('replset0.com, replset1.com, replset2.com/mydb?slaveOK=true?', ['collections']);

I'm not entirely sure what I need to do for the line after that. I'm guessing I would have to create an array that would contain the host name and port # for each member of the replica set (setup is primary, secondary, arbiter) such as:

var replSet = new replSet();
var replSet[0] = "server0:port0"
var replSet[1] = "server1.:port1"
var replSet[2] = "server2.:port2"

How would I go about detecting which node is the primary? Also if the primary were to fail, I would have to restart the node js application (using forever)?

like image 440
nocode Avatar asked Jun 01 '26 07:06

nocode


2 Answers

I found the answer as it's calling MongoDB's URI http://docs.mongodb.org/manual/reference/connection-string/

Should be something like:

var client = monq('mongodb://server0:port0,server1:port1,server2:port2/[dbname]?replicaSet=[replicaSet Name]
like image 159
nocode Avatar answered Jun 02 '26 22:06

nocode


First question: As long as you give it all of the members in the connection string, the mongojs driver should be able to figure out which one is primary. No need to figure it out yourself.

Second question: No, you don't have to restart the node app. The other members in the set will elect a new primary, although it takes time for mongo to detect failure and run the election.

For more information, see the mongodb docs on replica sets.

like image 36
MForMarlon Avatar answered Jun 02 '26 20:06

MForMarlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!