Lesson 42 of 50 – MongoDB Connection in Node.js
84% Completed
84%

MongoDB Connection in Node.js

Learn how to connect Node.js with MongoDB, create collections, insert documents, retrieve data, update records, delete records, and build a simple REST API.

What is MongoDB? MongoDB is a NoSQL database that stores data in flexible, document-based structures similar to JSON. Node.js applications can connect to MongoDB using the official MongoDB Node.js driver or the Mongoose library.

1. Why Use MongoDB with Node.js?

Node.js handles application logic and HTTP requests, while MongoDB stores the application's data.

Example Applications
  • Student management systems
  • Online learning platforms
  • Blog applications
  • E-commerce websites
  • Course management APIs
  • Content management systems

2. MongoDB vs MySQL

MongoDB MySQL
Document-oriented NoSQL database. Relational SQL database.
Stores documents in BSON format. Stores data in tables and rows.
Uses collections and documents. Uses tables and records.
Uses queries such as find(). Uses SQL statements such as SELECT.
Supports flexible document structures. Uses defined table schemas.

3. Install MongoDB

You can use either a local MongoDB installation or MongoDB Atlas.

Option 1: Local MongoDB
  1. Download MongoDB Community Server.
  2. Install and start the MongoDB server.
  3. Confirm that the server is running.
  4. Use the local connection string in your application.

Official download: MongoDB Community Server

Option 2: MongoDB Atlas
  1. Create an account on MongoDB Atlas.
  2. Create a database deployment.
  3. Create a database user.
  4. Configure network access for your development environment.
  5. Copy the application's connection string.

Official website: MongoDB Atlas

4. Create a Node.js Project

Create a folder named node-mongodb-app.

mkdir node-mongodb-app
cd node-mongodb-app
npm init -y

The npm init -y command creates a default package.json file.

5. Install MongoDB and Express

Install the official MongoDB driver and Express:

npm install mongodb express
The mongodb package is the official Node.js driver. It lets your Node.js application communicate directly with MongoDB.

6. Understand Databases, Collections, and Documents

MongoDB organizes data using three important concepts:

Concept Meaning Example
Database Contains collections. school_db
Collection Contains related documents. students
Document Stores individual data. A student's name and course.
Example Student Document
{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "course": "Node.js",
    "age": 20
}

MongoDB stores documents in BSON, a binary representation of JSON-like data. The driver converts documents to and from JavaScript objects.

7. Connect Node.js with MongoDB

Create a file named db.js.

db.js
const { MongoClient } = require("mongodb");

const uri = process.env.MONGODB_URI ||
    "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

let db;

async function connectDB() {
    if (!db) {
        await client.connect();

        db = client.db("school_db");

        console.log("MongoDB connected successfully!");
    }

    return db;
}

module.exports = {
    connectDB,
    client
};
Explanation
  • MongoClient is used to connect to MongoDB.
  • uri contains the database connection string.
  • client.connect() establishes the connection.
  • client.db("school_db") selects the database.
  • connectDB() returns the database object.
Important: The default connection string assumes MongoDB is running locally on port 27017. For MongoDB Atlas, set the MONGODB_URI environment variable to your actual connection string. Keep passwords and credentials private.

8. Test the MongoDB Connection

Create a file named test-db.js.

const { connectDB, client } = require("./db");

async function testConnection() {
    try {
        const db = await connectDB();

        await db.command({ ping: 1 });

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

testConnection();

Run the file:

node test-db.js
Expected Output
MongoDB connected successfully!
Database is ready!

9. Insert a Document into MongoDB

Use insertOne() to add one student document to the collection.

const { connectDB, client } = require("./db");

async function addStudent() {
    try {
        const db = await connectDB();

        const result = await db.collection("students").insertOne({
            name: "Rahul Kumar",
            email: "rahul@example.com",
            course: "Node.js",
            age: 20
        });

        console.log("Student added successfully!");
        console.log("Inserted ID:", result.insertedId);
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await client.close();
    }
}

addStudent();
Important Methods
  • db.collection("students") selects a collection.
  • insertOne() inserts one document.
  • result.insertedId returns the new document's ID.

10. Retrieve All Documents

Use find() and toArray() to retrieve the documents from a collection.

const { connectDB, client } = require("./db");

async function getStudents() {
    try {
        const db = await connectDB();

        const students = await db
            .collection("students")
            .find({})
            .toArray();

        console.log(students);
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await client.close();
    }
}

getStudents();
Example Output
[
    {
        _id: ObjectId("..."),
        name: "Rahul Kumar",
        email: "rahul@example.com",
        course: "Node.js",
        age: 20
    }
]

MongoDB automatically assigns an _id field to a document when you do not provide one.

11. Find a Student by Name

Use findOne() to retrieve the first document matching a condition.

const { connectDB, client } = require("./db");

async function findStudent() {
    try {
        const db = await connectDB();

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

        if (!student) {
            console.log("Student not found");
        } else {
            console.log(student);
        }
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await client.close();
    }
}

findStudent();
Remember: findOne() returns one matching document or null if no matching document exists.

12. Update a Document

Use updateOne() with $set to change selected fields in an existing document.

const { connectDB, client } = require("./db");

async function updateStudent() {
    try {
        const db = await connectDB();

        const result = await db.collection("students").updateOne(
            { email: "rahul@example.com" },
            {
                $set: {
                    course: "Full Stack Development"
                }
            }
        );

        if (result.matchedCount === 0) {
            console.log("Student not found");
        } else {
            console.log("Matched:", result.matchedCount);
            console.log("Modified:", result.modifiedCount);
        }
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await client.close();
    }
}

updateStudent();

The first argument identifies the document. The second argument contains the update operation.

13. Delete a Document

Use deleteOne() to remove one matching document.

const { connectDB, client } = require("./db");

async function deleteStudent() {
    try {
        const db = await connectDB();

        const result = await db.collection("students").deleteOne({
            email: "rahul@example.com"
        });

        if (result.deletedCount === 0) {
            console.log("Student not found");
        } else {
            console.log("Student deleted successfully!");
        }
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await client.close();
    }
}

deleteStudent();
Warning: Verify the filter before deleting documents. An incorrect filter can remove the wrong record. The examples in this lesson modify the database.

14. Create a REST API with Express and MongoDB

Now let's create an Express API that connects to MongoDB and provides endpoints for student records.

Create a file named server.js.

server.js
const express = require("express");
const { connectDB, client } = require("./db");

const app = express();

app.use(express.json());

// GET all students
app.get("/students", async (req, res) => {
    try {
        const db = await connectDB();

        const students = await db
            .collection("students")
            .find({})
            .toArray();

        res.json(students);
    } catch (error) {
        console.error(error);

        res.status(500).json({
            message: "Unable to retrieve students"
        });
    }
});

// POST a new student
app.post("/students", async (req, res) => {
    try {
        const { name, email, course } = req.body;

        if (
            typeof name !== "string" || !name.trim() ||
            typeof email !== "string" || !email.trim() ||
            typeof course !== "string" || !course.trim()
        ) {
            return res.status(400).json({
                message: "Name, email, and course are required"
            });
        }

        const db = await connectDB();

        const result = await db.collection("students").insertOne({
            name: name.trim(),
            email: email.trim(),
            course: course.trim()
        });

        res.status(201).json({
            message: "Student added successfully",
            id: result.insertedId
        });
    } catch (error) {
        console.error(error);

        res.status(500).json({
            message: "Unable to add student"
        });
    }
});

// Start the server after connecting to MongoDB
async function startServer() {
    try {
        await connectDB();

        const PORT = process.env.PORT || 5000;

        app.listen(PORT, () => {
            console.log(`Server running on port ${PORT}`);
        });
    } catch (error) {
        console.error("Unable to start server:", error.message);
        process.exitCode = 1;
    }
}

startServer();

Run the server:

node server.js
The server connects to MongoDB before accepting requests. If the initial connection fails, it reports the error instead of starting the API as if the database were ready.

15. Test the API Using Postman

Method URL Purpose
GET http://localhost:5000/students Retrieve all students.
POST http://localhost:5000/students Add a student.

For a POST request, select Body → raw → JSON and enter:

{
    "name": "Priya Sharma",
    "email": "priya@example.com",
    "course": "React"
}

Click Send. A successful insertion should return HTTP status code 201 Created.

16. MongoDB Query Methods

Method Purpose
insertOne() Insert one document.
insertMany() Insert multiple documents.
find() Retrieve matching documents using a cursor.
findOne() Retrieve one matching document.
updateOne() Update one matching document.
updateMany() Update multiple matching documents.
deleteOne() Delete one matching document.
deleteMany() Delete multiple matching documents.

17. Common MongoDB Connection Errors

Error Possible Solution
ECONNREFUSED Check that the local MongoDB server is running.
Authentication failed Check the database username, password, and authentication settings.
Server selection timeout Check the connection string, network access, and server availability.
Cannot find module 'mongodb' Run npm install mongodb in the project folder.
Invalid connection string Verify the URI format and encode special characters in credentials where required.

18. Practical Assignment

Student Management API

Create a student management application using Node.js, Express, and MongoDB.

  1. Create a database named school_db.
  2. Create a collection named students.
  3. Connect Node.js to MongoDB.
  4. Insert at least three student documents.
  5. Create a GET endpoint to retrieve all students.
  6. Create a POST endpoint to add a student.
  7. Validate the required fields.
  8. Test the API using Postman.
  9. Handle connection and server errors.
Example Student Document
{
    "name": "Aman Kumar",
    "email": "aman@example.com",
    "course": "Node.js"
}

Bonus Task: Add update and delete endpoints to complete the CRUD operations.

19. Lesson Summary

In this lesson, you learned how MongoDB stores documents, how to connect Node.js using the official MongoDB driver, how to perform CRUD operations, and how to create a basic Express API connected to MongoDB.

Test Your Knowledge – MongoDB

Select the correct answer for each question.

1. What is the name of the official MongoDB package used in this lesson?
2. Which MongoDB method inserts one document?
3. Which field uniquely identifies a MongoDB document by default?