使用node.js检索用于mongo查询的副本实例

mat*_*gus 7 mongodb node.js

我使用官方node.js mongodb客户端通过类似于的连接字符串执行针对集群的Mongo查询: mongodb://euwest1-01,euwest1-02,uswest2-01/dbname?replicaSet=mycluster&readPreference=nearest.如您所见,我在我的群集中包含一些不同的地理位置实例,"最近"应该保证选择正确的副本.

不过,我想知道哪一个用于执行任何查询,以便我可以在每个操作中包含用于执行查询的mongo副本.

黑客攻击Cursor对象,我可以用hacky方式得到我想要的东西:

const find = (query, callback) => {

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

但是我觉得这可以在任何时候打破不记录+似乎局限于光标互动(所以我不知道如何实现一个同样的findOne方法).

有人知道干净的方法吗?

小智 2

您可能对使用 APM 界面感兴趣。

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

这使您可以访问驱动程序运行的每个操作的上下文,这实际上适用于 APM 提供商,但如果您想跟踪或记录操作的执行方式,它可能对您有用。

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)
});
Run Code Online (Sandbox Code Playgroud)