Categories
Node.js Basics

Node.js Basics — Monitoring with MongoDB

Spread the love

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Monitoring with MongoDB

We can monitor MongoDB activities by listening to the events it emits.

For example, we can write:

const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);
const eventName = "serverDescriptionChanged";
client.on(eventName, event => {
  console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);
});

async function run() {
  try {
    await client.connect();
    const db = client.db("test");
    db.dropCollection('test');
    const testCollection = await db.collection('test');
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "apples", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = await testCollection.find();
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to watch for serverDescriptionChanged events and log the event data.

Then we get something like:

received serverDescriptionChanged: {
  "address": "localhost:27017",
  "previousDescription": {
    "address": "localhost:27017",
    "arbiters": [],
    "hosts": [],
    "passives": [],
    "type": "Unknown"
  },
  "newDescription": {
    "address": "localhost:27017",
    "arbiters": [],
    "hosts": [],
    "passives": [],
    "type": "Standalone"
  }
}

logged in the console.

Other events include:

  • serverOpening — Emitted when a connection to an instance opens.
  • serverClosed — Emitted when a connection to an instance closes.
  • serverDescriptionChanged — Emitted when an instance state changes
  • topologyOpening — Emitted prior to attempting a connection to an instance.topologyClosed — Emitted after all instance connections in the topology close.
  • topologyDescriptionChanged — Emitted when the topology changes, such as an election of a new primary or a mongos proxy disconnecting.
  • serverHeartbeatStarted — Emitted before issuing an isMaster command to a MongoDB instance.
  • serverHeartbeatSucceeded — Emitted when the isMaster command returns successfully from a MongoDB instance.
  • serverHeartbeatFailed — Created when an isMaster command issued to a specific MongoDB instance fails to return a successful response

The type field of the ServerDescription object is the event that has one of the following values:

  • Unknown — Unknown instance
  • Standalone — Standalone instanceMongosMongos proxy instance
  • PossiblePrimary — At least one server recognizes this as the primary, but is not yet verified by all instances.
  • RSPrimary — Primary instance
  • RSSecondary — Secondary instance
  • RSArbiter — Arbiter instance
  • RSOther
  • RSGhost

The topologyDescriptionChanged event has the type field in the TopologyDescription object which can be one of the following values:

  • Single — Standalone instance
  • ReplicaSetWithPrimary — Replica set with a primary
  • ReplicaSetNoPrimary — Replica set with no primary
  • Sharded — Sharded cluster
  • Unknown — Unknown topology

Conclusion

We can monitor for events with the MongoDB Node.js client to do monitoring.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *