Node js / MongoDB replica set array in javascript

2019-05-15 19:30发布

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)?

2条回答
Juvenile、少年°
2楼-- · 2019-05-15 19:46

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.

查看更多
迷人小祖宗
3楼-- · 2019-05-15 19:50

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]
查看更多
登录 后发表回答