MongoClient NodeJS open/close connection events

I want to connect to a MongoDB replica set (only one instance to be able to use Change Streams) while being able to be notified of connection lost/reconnect. I followed what described here:

const { MongoClient } = require("mongodb");

// Replace the following with your MongoDB deployment's connection
// string.
const uri =

const client = new MongoClient(uri);

// Replace <event name> with the name of the event you are subscribing to.
const eventName = "<event name>";
client.on(eventName, event => {
  console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);

async function run() {
  try {
    await client.connect();

    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();

I tried subscribing to events:

  • serverOpening and works fine
  • serverClosed and I can’t understand why but it does not work!!!

I would like to be able to get notified when the MongoDB connection is lost and/or restored and accordingly send a notification mail with “nodemailer”.
I was able to configure what desired in “mongoose” but, so far, not using official MongoDB drivers for NodeJS.

Hello @Sergio_Ferlito1,

I tried the same code with “serverClosed” event, it works fine. I am using MongoDB 4.2, NodeJS v12 and the MongoDB driver 3.6. I am connecting to a standalone server on localhost and default port.

const eventName2 = "serverClosed";
client.on(eventName2, event => {
  console.log(`.....received ${eventName2}: ${JSON.stringify(event, null, 2)}`);

This printed to the console:

.....received serverClosed: {
  "topologyId": 0,
  "address": "localhost:27017"


Also, works fine when connected to Atlas Cluster with a replica-set.

1 Like