Srikanth Technologies

Accessing MongoDB from Node.js

In this blog, we perform CRUD operations on documents in MongoDB using Node.js.

I assume you already installed MongoDB Community Edition or some other edition of MongoDB and created demo Database with a Document called books, which contains attributes - title, author and price.

Use MongoDB Compass - GUI for MongoDB - to access, and create Database, Collection and Documents.

Installing MongoDB driver

Install Node.js driver for MongoDB using NPM as follows:

Connect to MongoDB

The following code is used to connect to books document of demo database in MongoDB.

const { MongoClient } = require('mongodb')
const client = new MongoClient("mongodb://0.0.0.0:27017")
const database = client.db("demo")
console.log("Connected to Demo database!")
client.close()

Add new book

The following code inserts a new book to books document.

We create a function called addBook() with async keyword as it uses await keyword inside the function.

Function insertOne() takes a JavaScript object and inserts a new Document into books collection.

const { MongoClient } = require('mongodb')
const client = new MongoClient("mongodb://0.0.0.0:27017")

async function addBook(title, author, price) {
    try {
        const database = client.db("demo")   // connect to Database
        const booksCollection = database.collection('books')  // get collection
        const book = {
            title: `${title}`, author: `${author}`, price: price
        }
        const result = await booksCollection.insertOne(book) // insert document
        console.log(result)  // show result 
    } catch (ex) {
        console.log("Error -->" + ex)
    }
    finally {
        await client.close()
    }
}

// Call function with details of a book 
addBook('No rules rules', 'Reed Hastings', 800) 
When you run the above code, the result object returned by insertOne() is as follows:
{
  acknowledged: true,
  insertedId: new ObjectId('65c06f3ab700b8592d49cbcb')
}

Update an existing Book

The following code updates the price of an existing book selected based on its title.
const { MongoClient } = require('mongodb')

const client = new MongoClient("mongodb://0.0.0.0:27017")

async function updateBook(title, price) {
    try {
        const database = client.db("demo")
        const booksCollection = database.collection('books')
        const query = { title : `${title}`}
        const newValues = { $set: { price: `${price}` } }

        const result = await booksCollection.updateOne(query, newValues)
        console.log(result)
    } catch (ex) {
        console.log("Error -->" + ex)
    }
    finally {
        await client.close()
    }
}

updateBook('No rules rules', 700) 
When you run the above code, the result object returned by updateOne() is as follows. It shows one document matched the condition (matchedCount) and one document was modified (modifiedCount).
{
  acknowledged: true,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

Delete an existing Book

The following code is used to delete a Book with the given title.
const { MongoClient } = require('mongodb')

const client = new MongoClient("mongodb://0.0.0.0:27017")

async function deleteBook(title) {
    try {
        const database = client.db("demo")
        const booksCollection = database.collection('books')
        const query = { title : `${title}`}
        const result = await booksCollection.deleteOne(query)
        
        if (result.deletedCount === 1)   // Deleted successfully
            console.log(`Deleted ${title}`)
        else
            console.log(`Title - ${title} - not found!`)
    } catch (ex) {
        console.log("Error -->" + ex)
    }
    finally {
        await client.close()
    }
}

deleteBook('No rules rules') 

Retrieve costly books

The following code is used to retrieve books with price more than 600.
const { MongoClient } = require('mongodb')

const client = new MongoClient("mongodb://0.0.0.0:27017")

async function listCostlyBooks(price) {
    try {
        const database = client.db("demo")
        const booksCollection = database.collection('books')

        // value 1 selects the attribute and 0 omits it
        const options = {
           projection: { _id: 0, title: 1, author : 1, price: 1}   
        }

        const query = {price: { $gt: price }}
        const books = booksCollection.find(query, options)  // returns FindCursor
    
        // Access one document (book) at a time from FindCursor 
        for await (const book of books) {
            console.log(book)
        }
    } catch (ex) {
        console.log("Error -->" + ex)
    }
    finally {
        await client.close()
    }
}

listCostlyBooks(600) 
The above code displays books that have price greater than 600 as follows:
{
  title: 'No Filter: The Inside Story of Instagram',
  author: 'Sarah Frier',
  price: 700
}
{ title: 'No rules rules', 
  author: 'Reed Hastings', 
  price: 800 
}

For more information about MongoDB driver, visit https://www.mongodb.com/docs/drivers/node/current/

For more information about API Docs, visit https://mongodb.github.io/node-mongodb-native/6.3/

Keep Learning, Keep Growing

Srikanth Pragada