I need emit an event when the connection was connected and disconnected. My problem is to detect when the connection was reestablished.
The mongo drive emit um event when the connection was disconnected (on error), but it doesn't emit a event when the connection is reestablished.
MongoClient.connect(mongoUrl, function (err, db) {
if (err) {
console.log('Error on connecting to mongo!');
console.error(err);
reconnect();
return;
}
console.log('Mongo connected!');
emit('connected', db); // This event is emitted only on the first connection.
db.on('error', function (err) {
console.log('Mongo connection broken!');
console.error(err);
emit('disconnected');
});
}
Analyzing the code I discovered the serverConfig object.
db.serverConfig.on('reconnect', function() {
console.log('DB reconnected');
});
Is it a good practice to use this internal object?
Thanks.
According to Mongo driver developers, it's a good practice to use db.serverConfig to subscribe to the 'reconnect' event.
More details in: Database object emits a 'reconnect' event