Links

MongoDB Watcher

Send Messages on any changes in your Mongo Database via the Buildable SDK

Overview

In this example, we’re going to use the Buildable SDK to send messages when any operation is done in a Mongo Database. We’re going to do this in 2 easy steps:
  1. 1.
    Watch for changes in MongoDB
  2. 2.
    Emit the change information
For this example, you'll need a few things:
  • A Buildable account and Buildable Secret Key
  • A Mongo Database and Connection URI

Step 1: Watch for changes in MongoDB

Using the MongoDB NodeJS Driver, we’re going to connect to our MongoDB instance and open a Change Stream to listen for any changes.
import { MongoClient, Db } from "mongodb";
import { createClient } from "@buildable/messages";
const { emit } = createClient(process.env.BUILDABLE_SECRET_KEY);
// Connect to MongoDB
const getConnection = async (url: string, dbName: string): Promise<Db> => {
const client = new MongoClient(url);
await client.connect();
return client.db(dbName);
};
const main = async (): Promise<void> => {
const db = await getConnection(
process.env.MONGO_URI,
process.env.MONGO_DATABASE
);
const stream = db.watch();
// Open change stream
stream.on("change", async (change) => {
// Emit message here...
});
};
main().then(() => {
console.log("Listening for changes on the database...");
});

Step 2: Emit the change information

Inside the stream listener, we’re going to use the Buildable SDK to emit a message.
stream.on("change", async (change) => {
const { operationType, ns } = change;
const eventName = `${ns.db}.${ns.coll}.${operationType}`;
// Emit event
await emit(eventName, {
...change,
timestamp: Date.now(),
});
console.log("Operation: ", change);
});

You're done! Here's the final Code

import { MongoClient, Db } from "mongodb";
import { createClient } from "@buildable/messages";
const { emit } = createClient(process.env.BUILDABLE_SECRET_KEY);
// Connect to MongoDB
const getConnection = async (url: string, dbName: string): Promise<Db> => {
const client = new MongoClient(url);
await client.connect();
return client.db(dbName);
};
const main = async (): Promise<void> => {
const db = await getConnection(
process.env.MONGO_URI,
process.env.MONGO_DATABASE
);
const stream = db.watch();
// Open change stream
stream.on("change", async (change) => {
const { operationType, ns } = change;
const eventName = `${ns.db}.${ns.coll}.${operationType}`;
// Emit event
await emit(eventName, {
...change,
timestamp: Date.now(),
});
console.log("Operation: ", change);
});
};
main().then(() => {
console.log("Listening for changes on the database...");
});

What's Next?

Now that messages will be emitted on any change to your Mongo Database, read on to see how you can transact on these messages: