how to find the connected hostname for mongo instance using node.js

1,249 views
Skip to first unread message

Amit Agarwal

unread,
Oct 24, 2016, 5:48:00 PM10/24/16
to mongodb-user
Hi,

I have 3 node replicates and i am using all the host in my connection string.
Once i execute my node.js script i want to see which particular host it got connected to.

I can fire the following command in mongo shell but same is not working in node.js script, mostly says like "function is not defined"

hostname

db.hostInfo().system.hostname
rs.status().members.find(r=>r.state===1).name

TypeError: db.hostInfo is not a function

ReferenceError: hostname is not defined



Can someone help me how i can find the connected mongo instance server name using the node.js script?


Thanks,

Amit


Wan Bachtiar

unread,
Nov 1, 2016, 9:46:12 PM11/1/16
to mongodb-user

Can someone help me how i can find the connected mongo instance server name using the node.js script?

Hi Amit,

You can try running the isMaster() command to retrieve some information about the replica set you’re connecting to. For example:

MongoClient.connect(mongo_url, function(err, db) {
    assert.equal(null, err);

    db.command({'ismaster':1}, function(err, result){
        console.log(result);
    });
    db.close();
});

The code above should print out an output similar to :

{ hosts: [ 'host1:28001', 'host2:28002', 'host3:28003' ],
  setName: 'replicaSetName',
  setVersion: 1,
  ismaster: true,
  secondary: false,
  primary: 'host1:27001',
  me: 'host1:27001',
  electionId: 7fffffff0000000000000004,
  maxBsonObjectSize: 16777216,
  maxMessageSizeBytes: 48000000,
  maxWriteBatchSize: 1000,
  localTime: 2016-11-02T01:37:14.364Z,
  maxWireVersion: 4,
  minWireVersion: 0,
  ok: 1 }

The value of ismaster, primary and me are most likely what you’re after.

The snippet above was written for MongoDB Node.js driver v2.2 and MongoDB v3.2.x. If you have further questions, could you provide:

  • Specific MongoDB Node.js driver version
  • Specific MongoDB server version

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages