Listen to reconnect events in MongoDB driver

后端 未结 1 1845
名媛妹妹
名媛妹妹 2021-01-06 02:48

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.

相关标签:
1条回答
  • 2021-01-06 03:17

    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.

    0 讨论(0)
提交回复
热议问题