Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to reconnect events in MongoDB driver

I would like to add event listeners to a MongoDB connection to run something when the connection drops, each reconnection attempt and at a successful reconnection attempt.

I read all the official docs and the API, but I can't find a solution.

Currently, I have this, but only the timeout event works. // If we didn't already initialize a 'MongoClient', initialize one and save it. if(!this.client) this.client = new MongoClient();

    this.connection = await this.client.connect(connectionString, this.settings);

    this.client.server.on('connect', event => {
        console.log(event);
    });

    this.client.server.on('error', event => {
        console.log(event);
    });

    this.client.server.on('reconnect', event => {
        console.log(event);
    });

    this.client.server.on('connections', event => {
        console.log(event);
    });

    this.client.server.on('timeout', event => {
        console.log(event);
    });

    this.client.server.on('all', event => {
        console.log(event);
    });

I tried the events listed here, and they work, but there is no "reconnect" event: http://mongodb.github.io/node-mongodb-native/2.2/reference/management/sdam-monitoring/

like image 221
Samuel E. Avatar asked Jul 16 '17 01:07

Samuel E.


People also ask

Which drivers are useful to connect node js with MongoDB?

Connect your Node. js applications to MongoDB and work with your data using the Node. js driver. The driver features an asynchronous API that you can use to access method return values through Promises or specify callbacks to access them when communicating with MongoDB.

How do I fix Mongoserverselectionerror?

My solution to this error was to whitelist my current IP address in the MongoDB cluster where my error was occurring. Upon starting up my node. js application, my server started, as usual. However, my app timed out when it would then try to connect to my MongoDB cluster.


1 Answers

Sure you can. Basically though you need to tap into the EventEmitter at a lower level than basically off the MongoClient itself.

You can clearly see that such things exist since they are visible in "logging", which can be turned on in the driver via the setting:

{ "loggerLevel": "info" }

From then it's really just a matter of tapping into the actual source emitter. I've done these in the following listing, as well as including a little trick for getting the enumerated events from a given emitted, which was admittedly used by myself in tracking this down:

const MongoClient = require('mongodb').MongoClient;

function patchEmitter(emitter) {
  var oldEmit = emitter.emit;

  emitter.emit = function() {
    var emitArgs = arguments;

    console.log(emitArgs);

    oldEmit.apply(emitter, arguments);
  }

}


(async function() {

  let db;

  try {

    const client = new MongoClient();

    client.on('serverOpening', () => console.log('connected') );

    db = await client.connect('mongodb://localhost/test', {
      //loggerLevel: 'info'
    });

    //patchEmitter(db.s.topology);

    db.s.topology.on('close', () => console.log('Connection closed') );
    db.s.topology.on('reconnect', () => console.log('Reconnected') );


  } catch(e) {
    console.error(e)
  }

})()

So those two listeners defined:

    db.s.topology.on('close', () => console.log('Connection closed') );
    db.s.topology.on('reconnect', () => console.log('Reconnected') );

Are going to fire when the connection drops, and when an reconnect is achieved. There are also other things like reconnect attempts which are also in the event emitter just like you would see with the loggerLevel setting turned on.

like image 138
Neil Lunn Avatar answered Nov 12 '22 00:11

Neil Lunn