Search code examples
javascriptnode.jsmongodbmongoskin

mongoskin and connection issue to mongodb replica cluster


I am using mongoskin npm module to connect to my mongo database replica cluster. I tried all the possible approach however my nodejs code is not able to make connection. I am able to connect same primary database using standalone connection however it fails when I try using replica server. Following are more details

Code working for standalone: 
var express = require('express');
var app = express();
var mongo = require('mongoskin');
//connect primary as  standalone 
var db = mongo.db("mongodb://username:[email protected]:27017/bhs", {native_parser: true});

app.get('/', function (req, res) {
    db.bind('goalsfrequencymappings');
    db.goalsfrequencymappings.find().toArray(function (err, items) {
        res.json(items);
        db.close();
    });


});

var server = app.listen(8080, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);

});

Code not working as replica server:

var express = require('express');
var mongo = require('mongoskin');
var app = express();
var Server = mongo.Server;
var Db = mongo.Db;
var ReplSetServers = mongo.ReplSetServers;


var replSet = new ReplSetServers([
    new Server('username:[email protected]:27017', 27017),
    new Server('username:[email protected]', 27017),
    new Server('username:[email protected]', 27017)
]);


var db = new Db('bhs', replSet, {w: 0, native_parser: (process.env['TEST_NATIVE'] != null)});

app.get('/', function (req, res) {

    db.collection('goalsfrequencymappings').find().toArray(function (err, items) {

        if(err){
            console.log("error :"+err);
            res.json(err);

        } else {
            console.log("items :"+items);
          res.json(items);  
        }

        db.close();
    });

});

var server = app.listen(8080, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);

});

It print following error:

Example app listening at http://0.0.0.0:8080
error :Error: No valid replicaset instance servers found

When I connect to cluster database using cli and run the status and config command then it looks good.

myReplicaCluster:PRIMARY> rs.status();
{
    "set" : "myReplicaCluster",
    "date" : ISODate("2015-05-22T05:18:47Z"),
    "myState" : 1,
    "members" : [
        {
            "_id" : 0,
            "name" : "177.77.66.9:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 6415902,
            "optime" : Timestamp(1432268531, 1),
            "optimeDate" : ISODate("2015-05-22T04:22:11Z"),
            "electionTime" : Timestamp(1425856025, 11),
            "electionDate" : ISODate("2015-03-08T23:07:05Z"),
            "self" : true
        },
        {
            "_id" : 1,
            "name" : "88.052.72.91:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 6415566,
            "optime" : Timestamp(1432268531, 1),
            "optimeDate" : ISODate("2015-05-22T04:22:11Z"),
            "lastHeartbeat" : ISODate("2015-05-22T05:18:46Z"),
            "lastHeartbeatRecv" : ISODate("2015-05-22T05:18:47Z"),
            "pingMs" : 4,
            "syncingTo" : "177.77.66.9:27017"
        },
        {
            "_id" : 2,
            "name" : "95.46.865.455:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 6415543,
            "optime" : Timestamp(1432268531, 1),
            "optimeDate" : ISODate("2015-05-22T04:22:11Z"),
            "lastHeartbeat" : ISODate("2015-05-22T05:18:46Z"),
            "lastHeartbeatRecv" : ISODate("2015-05-22T05:18:46Z"),
            "pingMs" : 0,
            "syncingTo" : "177.77.66.9:27017"
        }
    ],
    "ok" : 1
}
myReplicaCluster:PRIMARY> rs.config();
{
    "_id" : "myReplicaCluster",
    "version" : 5,
    "members" : [
        {
            "_id" : 0,
            "host" : "177.77.66.9:27017"
        },
        {
            "_id" : 1,
            "host" : "88.052.72.91:27017"
        },
        {
            "_id" : 2,
            "host" : "95.46.865.455:27017"
        }
    ]
}

Please help.


Solution

  • After following other post, I realized that I was passing username,password for each seeds which was not required. By simply following the mongodb connection pool syntax it worked. Following is details of my modified code which is working fine and running on production.

     //Set seed mongo replicas.
    url = 'mongodb://username:[email protected]:27017,88.052.72.91:27017,95.46.865.455:27017/dbname?replicaSet=yourReplicaCluster';
    
    // Connect DB
    var db = mongoskin.db(url, {native_parser: true, 'auto_reconnect': true, 'poolSize': 100, socketOptions: {
            keepAlive: 50,
            connectTimeoutMS: 1000,
            socketTimeoutMS: 0
        }});
    
    // Get documents 
        getDocumentByQuery: function (collection, callback) {
            var query={};
            //Add additional filter to exclude soft deleted documents
            query.isDeleted = {$ne: true}
            DBModule.db.collection(collection).find(query).toArray(function (err, docuemnts) {
                if (!err) {
                    callback(null, docuemnts);
                } else {
                    callback(err, null);
                }
            });
        }