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 =
"mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
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();
}
}
run().catch(console.dir);
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.