Simple CRUD operation of MongoDB SaaS in NodeJs

Simple CRUD operation of MongoDB SaaS in NodeJs

As a prerequisite to this we need to setup our database in MongoDB SaaS from account.mongodb.com/account/login.

We need to have a Mongo DB server URL which we can build as MONGO_DB_URL here

const MONGO_DATABASE_USER = 'common'
const MONGO_DATABASE_PASSWORD = 'Anb5YIiydhFccFxm'
const MONGO_DATABASE_NAME = 'common'
const MONGO_DB_URL = `mongodb+srv://${MONGO_DATABASE_USER}:${MONGO_DATABASE_PASSWORD}@cluster.ag12b.mongodb.net/${MONGO_DATABASE_NAME}?retryWrites=true&w=majority`

Once you have the URL, we will initialize the mongodb server connection in our NodeJs app as follows:

import { MONGO_DB_URL } from "./db_config";

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

/**
 * The Mongo Client you will use to interact with your database
 * See https://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html for more details
 * In case: '[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated...'
 * pass option { useUnifiedTopology: true } to the MongoClient constructor.
 * const client =  new MongoClient(uri, {useUnifiedTopology: true})
 */
const client = new MongoClient(MONGO_DB_URL);

(async function init() {
  try {
    // Connect to the MongoDB cluster
    await client.connect();
  } catch (err) {
    console.error("Error occurred");
    console.error(err);
  }
})();

async function run(callback) {
  try {
    await callback(client);
  } catch (err) {
    console.error("Error occurred");
    console.error(err);
  }
}

export async function mongodb(callback) {
  return await run(callback);
}

const cleanup = (event) => {
  // SIGINT is sent for example when you Ctrl+C a running process from the command line.
  client.close(); // Close MongodDB Connection when Process ends
  process.exit(); // Exit with default success-code '0'.
};

process.on("SIGINT", cleanup);
process.on("SIGTERM", cleanup);

Lets breakdown the above code as follows:

  1. mongodb function: this is exported for use in routes where we will trigger an action on the database.
  2. run function: this is a wrapper for executing the callback function which specifies the action on mongodb and error handling for the same.
  3. init function: this is an IIFE which is used to initialize a connection to the database server
  4. cleanup function: this is an error handler which will be used to close the connection in case the server crashes

Now we will see how to use the above mongodb function we have exposed. Consider the following routes:

Fetching data

You can fetch the data as follows:

export async function fetchTodos(userId) {
  let result = null
  await mongodb(async (client) => {
    result = await client
      .db('todos_db')
      .collection('todos_clln')
      .find({ 'userId': userId })
      .toArray()
    console.log(`Fetched todos: ${result.length}`)
  })
  return result
}

Inserting record

You can insert a record into the database as follows:

export async function createTodo(todo) {
  let result = null
  await mongodb(async (client) => {
    result = await client
      .db('todos_db')
      .collection('todos_clln')
      .insertOne(todo)
    console.dir(result)
    console.log(
      `New todo created with the following id: ${result.insertedId}`
    )
  })
  return result
}

Updating record

You can update an existing record as follows:

export async function updateTodo({ todoId, status }) {
  let result = null
  await mongodb(async (client) => {
    const newStatus = status === PENDING ? DONE : PENDING
    result = await client
      .db('todos_db')
      .collection('todos_clln')
      .updateOne({ _id: ObjectId(todoId) }, { $set: { status: newStatus } })
    console.log(`Updated todo: ${todoId}`)
  })
  return result
}

Deleting record

You can delete a record as follows:

export async function deleteTodo(todoId) {
  let result = null
  await mongodb(async (client) => {
    result = await client
      .db('todos_db')
      .collection('todos_clln')
      .deleteOne({ _id: todoId })
    console.log(`Deleting todo: ${todoId}`)
  })
  return result
}

This will complete your basic crud operations on a Mongo database. Hope this was helpful to you. Send me your suggestions and appreciations in the comments below.

Did you find this article valuable?

Support JAGDEEP BISHT by becoming a sponsor. Any amount is appreciated!