title: Monitoring mongodb connection to a replicaset in NodeJS
body: <p>I want to connect to a MongoDB replica set (only one instance to works with change streams) while being able to be notified of connection lost/reconnect.
  I followed what described <a href="https://docs.mongodb.com/drivers/node/fundamentals/monitoring" rel="nofollow noreferrer">here</a>:</p>
  <pre><code>const { MongoClient } = require(&quot;mongodb&quot;);
  
  // Replace the following with your MongoDB deployment's connection
  // string.
  const uri =
    &quot;mongodb+srv://&lt;clusterUrl&gt;/?replicaSet=rs&amp;writeConcern=majority&quot;;
  
  const client = new MongoClient(uri);
  
  // Replace &lt;event name&gt; with the name of the event you are subscribing to.
  const eventName = &quot;&lt;event name&gt;&quot;;
  client.on(eventName, event =&gt; {
    console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);
  });
  
  async function run() {
    try {
      await client.connect();
  
      // Establish and verify connection
      await client.db(&quot;admin&quot;).command({ ping: 1 });
      console.log(&quot;Connected successfully&quot;);
    } finally {
      // Ensures that the client will close when you finish/error
      await client.close();
    }
  }
  run().catch(console.dir);
  </code></pre>
  <p>I tried subscribing to events:</p>
  <ul>
  <li><code>serverOpening</code> and works fine</li>
  <li><code>serverClosed</code> and <strong>I can't understand why but it does not work!!!</strong></li>
  </ul>
  <p>No &quot;reconnect&quot; event, any solution?</p>