Lesson 31 of 50 – MongoDB with Node.js
62%

MongoDB with Node.js

Node.js allows developers to execute JavaScript outside the browser. By using the official MongoDB Node.js driver, we can connect Node.js applications to MongoDB databases and perform operations such as inserting, reading, updating, and deleting documents.

1. What Is Node.js?

Node.js is a JavaScript runtime built on the V8 JavaScript engine. It is commonly used to develop backend applications, REST APIs, and database-driven websites.

Common uses of Node.js include:

  • Building web servers and REST APIs.
  • Connecting applications to MongoDB.
  • Developing real-time applications.
  • Creating backend services for websites and mobile apps.
  • Processing requests from frontend applications.

MongoDB stores the application data, while Node.js runs the backend code that communicates with the database.

2. Install Node.js

Download and install the current supported Node.js LTS version from the official website:

Visit the official Node.js website

After installation, open your terminal or command prompt.

Check the Node.js version:

node --version

Check the npm version:

npm --version

npm is the package manager commonly used to install JavaScript libraries and tools.

3. Create a Node.js Project

Create a new folder for your MongoDB and Node.js practice project.

mkdir mongodb-node-project
cd mongodb-node-project

Initialize the project:

npm init -y

This command creates a package.json file containing project information and configuration.

Your project will eventually contain files such as package.json, server.js, and other application files.

4. Install the MongoDB Driver

The official MongoDB Node.js driver lets a Node.js application communicate with a MongoDB server.

Install it using npm:

npm install mongodb

This command adds the MongoDB driver to your project dependencies.

You can now import the driver's MongoClient class into your JavaScript application.

5. Connect Node.js to MongoDB

Create a file named server.js in your project folder.

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();

        console.log("Connected to MongoDB successfully!");

        const db = client.db("school");

        console.log("Database selected:", db.databaseName);

    } catch (error) {
        console.error("MongoDB connection failed:", error.message);
    } finally {
        await client.close();
    }
}

main();

Run the program:

node server.js

Expected output when the local server is available:

Connected to MongoDB successfully!
Database selected: school

Important: Make sure MongoDB is running on your computer. This connection string is for a local MongoDB server. Use your actual connection string if your database is hosted elsewhere.

6. Insert a Document from Node.js

Use insertOne() to insert one document into a MongoDB collection.

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

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();

        const db = client.db("school");
        const students = db.collection("node_students");

        const result = await students.insertOne({
            name: "Rahul",
            age: 20,
            course: "Java",
            fees: 5000
        });

        console.log("Inserted document ID:", result.insertedId);

    } catch (error) {
        console.error(error);
    } finally {
        await client.close();
    }
}

main();

Save this code in server.js and execute node server.js.

Each successful execution inserts another document. Run the insertion example only when you intend to add a new student record.

7. Insert Multiple Documents

Use insertMany() when you want to insert multiple documents in one operation.

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

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();

        const db = client.db("school");
        const students = db.collection("node_students");

        const result = await students.insertMany([
            {
                name: "Priya",
                age: 21,
                course: "Python"
            },
            {
                name: "Aman",
                age: 19,
                course: "Java"
            }
        ]);

        console.log("Inserted count:", result.insertedCount);

    } catch (error) {
        console.error(error);
    } finally {
        await client.close();
    }
}

main();

The insertedCount property indicates how many documents were inserted successfully.

Note: Repeated execution inserts additional records. Avoid repeatedly running this example if you want to keep only the original sample data.

8. Read Documents Using find()

Use find() to retrieve documents that match a filter. The returned cursor can be converted to an array using toArray().

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

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();

        const db = client.db("school");
        const students = db.collection("node_students");

        const result = await students.find().toArray();

        console.log(result);

    } catch (error) {
        console.error(error);
    } finally {
        await client.close();
    }
}

main();

Find only Java students:

const result = await students.find({
    course: "Java"
}).toArray();

console.log(result);

An empty filter, {}, matches all documents in the collection.

9. Find One Document

The findOne() method returns one matching document or null if no document matches.

const student = await students.findOne({
    name: "Rahul"
});

if (student) {
    console.log("Student found:", student);
} else {
    console.log("Student not found.");
}

Use findOne() when your application needs a single matching document rather than a cursor containing multiple results.

10. Update Documents

Use updateOne() to modify the first matching document.

const result = await students.updateOne(
    { name: "Rahul" },
    { $set: { fees: 6000 } }
);

console.log("Matched:", result.matchedCount);
console.log("Modified:", result.modifiedCount);

The $set operator changes the specified field while leaving other fields unchanged.

The result's matchedCount shows how many documents matched the filter. The modifiedCount shows how many documents were actually changed.

11. Delete Documents

Use deleteOne() to delete the first document matching a filter.

const result = await students.deleteOne({
    name: "Aman"
});

console.log("Deleted:", result.deletedCount);

A value of 1 means one document was deleted. A value of 0 means no document matched.

Warning: Always use a specific filter when deleting documents. Be especially careful with deleteMany({}), which deletes every document in the collection.

12. Use async and await

Database operations take time because Node.js communicates with a database server. The MongoDB driver provides asynchronous methods that return promises.

async function getStudents(students) {
    const result = await students.find().toArray();
    return result;
}

The async keyword allows a function to use await. The await keyword pauses that asynchronous function until the promise settles.

Using try...catch helps handle errors such as failed connections, invalid queries, and database operation failures.

13. Complete CRUD Example

This example demonstrates creating, reading, updating, and deleting a single student record. It uses a unique practice identifier so it does not need to delete unrelated sample documents.

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

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function main() {
    const practiceId = "NODE-PRACTICE-001";

    try {
        await client.connect();

        const db = client.db("school");
        const students = db.collection("node_students");

        // CREATE
        await students.updateOne(
            { practiceId: practiceId },
            {
                $set: {
                    name: "Kiran",
                    age: 22,
                    course: "JavaScript"
                }
            },
            { upsert: true }
        );

        console.log("Student created or reset.");

        // READ
        let student = await students.findOne({
            practiceId: practiceId
        });

        console.log("Student:", student);

        // UPDATE
        await students.updateOne(
            { practiceId: practiceId },
            { $set: { age: 23 } }
        );

        student = await students.findOne({
            practiceId: practiceId
        });

        console.log("Updated student:", student);

        // DELETE
        const result = await students.deleteOne({
            practiceId: practiceId
        });

        console.log("Deleted count:", result.deletedCount);

    } catch (error) {
        console.error("Operation failed:", error.message);
    } finally {
        await client.close();
    }
}

main();

The upsert: true option creates a document if no document matches the filter. Otherwise, it updates the matching document.

For this practice example, the identifier should be reserved for the exercise. In a real application, enforce uniqueness for identifiers that must be unique.

14. Close the Database Connection

Close the MongoDB client when your script has finished its database work.

await client.close();

In a short script, closing the client in a finally block helps ensure cleanup even when an error occurs.

In a long-running web server, applications usually create a shared MongoDB client during startup and reuse its connection pool for requests, then close it when the application shuts down.

15. Practical Assignment

Complete the following tasks using Node.js and MongoDB:

  1. Install Node.js and initialize a project.
  2. Install the official MongoDB Node.js driver.
  3. Connect to a MongoDB database named school.
  4. Insert three student documents.
  5. Display all students using find().
  6. Find a student by name using findOne().
  7. Update one student's course or fees.
  8. Delete a student using a specific filter.
  9. Handle errors using try...catch.
  10. Close the database client correctly.

🧠 Quick Quiz

1. Which package connects Node.js to MongoDB using the official driver?




2. Which method inserts one document into a collection?




3. Why is await used with asynchronous database operations?