matteofigus matteofigus - 1 month ago 8
Node.js Question

Retrieve which replica instance was used for mongo query using node.js

I use the official node.js mongodb client for performing Mongo queries targeting a cluster via a connection string similar to:

mongodb://euwest1-01,euwest1-02,uswest2-01/dbname?replicaSet=mycluster&readPreference=nearest
. As you see, I include in my cluster some differently geo-located instances and "nearest" should guarantee the right replica to be picked.

Nevertheless, I would like to know which one was used to perform any query, so that I can include to each of my operations' log the mongo replica that was used to perform the query.

Hacking around the Cursor object, I can get what I want in an hacky way:

const find = (query, callback) => {

let cursor = coll.find(query);
cursor.toArray((err, items) => {
console.log(cursor.server.ismaster.me);
callback(err, items);
});
};


But I feel like this can break in any moment as not documented + it seems limited to the Cursor interactions (so I wouldn't know how to achieve the same for a
findOne
method).

Is anyone aware about a clean way to do this?

Answer

You might be interested in using the APM interface.

http://mongodb.github.io/node-mongodb-native/2.2/reference/management/apm/

This lets you access the context of each operation being run by the driver and is really meant for APM providers but if you want to keep track or log how your ops are executing it might be useful for you.

var listener = require('mongodb').instrument({
  operationIdGenerator: {
    operationId: 1,

    next: function() {
      return this.operationId++;
    }
  },

  timestampGenerator: {
    current: function() {
      return new Date().getTime();
    },

    duration: function(start, end) {
      return end - start;
    }
  }  
}, function(err, instrumentations) {
  // Instrument the driver  
});

listener.on('started', function(event) {
  // command start event (see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst)
});

listener.on('succeeded', function(event) {
  // command success event (see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst)
});

listener.on('failed', function(event) {
  // command failure event (see https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst)
});

Comments