Node js / MongoDB replica set array in javascript

倾然丶 夕夏残阳落幕 提交于 2019-12-10 10:17:51

问题


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


回答1:


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]



回答2:


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.



来源:https://stackoverflow.com/questions/19666210/node-js-mongodb-replica-set-array-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!