MongoDB with Express.js Practice Questions with Solutions

Introduction

MongoDB with Express.js is a common combination for building backend applications and REST APIs using JavaScript. Express.js handles HTTP requests and routes, while MongoDB stores application data. In this chapter, you will practice setting up Express.js with MongoDB, connecting the database, creating API routes, inserting documents, reading data, updating documents, and deleting records. MongoDB with Express.js Practice Questions with Solutions to help you build concepts.

Q1. Create an Express.js Project

Problem Statement

Create a new Node.js project and install Express.js and the MongoDB Node.js driver.

MongoDB Command / Query

Create a project:

mkdir express-mongodb-practice
cd express-mongodb-practice
npm init -y

Install the required packages:

npm install express mongodb

Expected Output

Your project should contain:

express-mongodb-practice/
│
├── node_modules/
├── package.json
└── package-lock.json

Explanation

express is used to create the web server and API routes.

mongodb is the official MongoDB driver used by Node.js applications to communicate with MongoDB.


Q2. Create a Basic Express.js Server

Problem Statement

Create an Express.js server that displays a simple message when someone visits the home route.

MongoDB Command / Query

Create app.js:

const express = require("express");

const app = express();

app.get("/", (req, res) => {
    res.send("MongoDB and Express.js Practice");
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Run:

node app.js

Expected Output

Terminal:

Server running on port 3000

Browser response:

MongoDB and Express.js Practice

Explanation

Express creates the web server and handles HTTP requests.


Q3. Connect Express.js to MongoDB

Problem Statement

Connect an Express.js application to a local MongoDB server.

MongoDB Command / Query

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

const app = express();

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

async function connectDB() {
    await client.connect();
    console.log("Connected to MongoDB");
}

connectDB();

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Expected Output

Connected to MongoDB
Server running on port 3000

Explanation

MongoClient establishes the connection between the Express.js application and MongoDB.


Q4. Select a Database and Collection

Problem Statement

Access the school database and its students collection from Express.js.

MongoDB Command / Query

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

console.log("Database and collection ready");

Expected Output

Database and collection ready

Explanation

The following statements select the database and collection:

client.db("school")

and:

db.collection("students")


Q5. Create a GET API to Read Students

Problem Statement

Create an Express.js GET API at /students that returns all students from MongoDB.

MongoDB Command / Query

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

const app = express();

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

let students;

async function startServer() {
    await client.connect();

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

    app.get("/students", async (req, res) => {
        const result = await students.find({}).toArray();
        res.json(result);
    });

    app.listen(3000, () => {
        console.log("Server running on port 3000");
    });
}

startServer();

Expected Output

Request:

GET /students

Response:

[
    {
        "_id": "ObjectId(...)",
        "name": "Rahul",
        "age": 17,
        "course": "Python"
    },
    {
        "_id": "ObjectId(...)",
        "name": "Neha",
        "age": 16,
        "course": "Java"
    }
]

Explanation

The Express route receives the request and MongoDB retrieves the documents using:

students.find({}).toArray()

res.json() sends the data back as JSON.


Q6. Create a POST API to Insert a Student

Problem Statement

Create a POST API that receives student information and inserts it into MongoDB.

MongoDB Command / Query

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

const app = express();

app.use(express.json());

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

let students;

async function startServer() {
    await client.connect();

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

    app.post("/students", async (req, res) => {
        const student = req.body;

        const result = await students.insertOne(student);

        res.json({
            message: "Student inserted successfully",
            insertedId: result.insertedId
        });
    });

    app.listen(3000, () => {
        console.log("Server running on port 3000");
    });
}

startServer();

Expected Output

Send a POST request to:

/students

with JSON:

{
    "name": "Aman",
    "age": 15,
    "course": "C++"
}

Response:

{
    "message": "Student inserted successfully",
    "insertedId": "ObjectId(...)"
}

Explanation

This middleware:

app.use(express.json());

allows Express.js to read JSON request bodies.

The data is then available through:

req.body


Q7. Create a GET API for One Student

Problem Statement

Create an API that finds one student using their name.

MongoDB Command / Query

app.get("/students/:name", async (req, res) => {
    const name = req.params.name;

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

    if (!student) {
        return res.status(404).json({
            message: "Student not found"
        });
    }

    res.json(student);
});

Expected Output

Request:

GET /students/Rahul

Response:

{
    "_id": "ObjectId(...)",
    "name": "Rahul",
    "age": 17,
    "course": "Python"
}

Explanation

req.params.name gets the name value from the URL.

The MongoDB query:

students.findOne({
    name: name
})

searches for one matching document.


Q8. Create a PUT API to Update a Student

Problem Statement

Create an API that updates a student’s age using their name.

MongoDB Command / Query

app.put("/students/:name", async (req, res) => {
    const name = req.params.name;

    const result = await students.updateOne(
        {
            name: name
        },
        {
            $set: {
                age: req.body.age
            }
        }
    );

    res.json({
        matched: result.matchedCount,
        modified: result.modifiedCount
    });
});

Expected Output

Request:

PUT /students/Rahul

JSON body:

{
    "age": 18
}

Response:

{
    "matched": 1,
    "modified": 1
}

Explanation

Express receives the request, while MongoDB performs the update using updateOne() and $set.


Q9. Create a DELETE API

Problem Statement

Create an API that deletes a student using their name.

MongoDB Command / Query

app.delete("/students/:name", async (req, res) => {
    const name = req.params.name;

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

    if (result.deletedCount === 0) {
        return res.status(404).json({
            message: "Student not found"
        });
    }

    res.json({
        message: "Student deleted successfully"
    });
});

Expected Output

Request:

DELETE /students/Aman

Response:

{
    "message": "Student deleted successfully"
}

Explanation

deleteOne() removes the first document matching the specified filter.


Q10. Build a Complete Student CRUD API

Problem Statement

Create a simple Express.js application that connects to MongoDB and provides APIs for creating, reading, updating, and deleting students.

MongoDB Command / Query

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

const app = express();

app.use(express.json());

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

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

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

        // CREATE
        app.post("/students", async (req, res) => {
            const result = await students.insertOne(req.body);

            res.status(201).json({
                message: "Student created",
                id: result.insertedId
            });
        });

        // READ ALL
        app.get("/students", async (req, res) => {
            const result = await students.find({}).toArray();

            res.json(result);
        });

        // READ ONE
        app.get("/students/:name", async (req, res) => {
            const student = await students.findOne({
                name: req.params.name
            });

            if (!student) {
                return res.status(404).json({
                    message: "Student not found"
                });
            }

            res.json(student);
        });

        // UPDATE
        app.put("/students/:name", async (req, res) => {
            const result = await students.updateOne(
                {
                    name: req.params.name
                },
                {
                    $set: req.body
                }
            );

            res.json({
                matched: result.matchedCount,
                modified: result.modifiedCount
            });
        });

        // DELETE
        app.delete("/students/:name", async (req, res) => {
            const result = await students.deleteOne({
                name: req.params.name
            });

            if (result.deletedCount === 0) {
                return res.status(404).json({
                    message: "Student not found"
                });
            }

            res.json({
                message: "Student deleted"
            });
        });

        app.listen(3000, () => {
            console.log("Server running on port 3000");
        });

    } catch (error) {
        console.error("Database connection failed:", error);
    }
}

startServer();

Expected Output

When the application starts:

Server running on port 3000

The API provides:

MethodEndpointPurpose
POST/studentsCreate a student
GET/studentsGet all students
GET/students/:nameGet one student
PUT/students/:nameUpdate a student
DELETE/students/:nameDelete a student

Example POST request:

{
    "name": "Ravi",
    "age": 16,
    "course": "Node.js"
}

Example response:

{
    "message": "Student created",
    "id": "ObjectId(...)"
}

Explanation

This example connects all the important concepts:

Client
   ↓
Express.js Route
   ↓
MongoDB Node.js Driver
   ↓
MongoDB
   ↓
Response

Express.js handles the HTTP/API layer, while MongoDB handles data storage.

Key Takeaways

  • Express.js can be used with MongoDB to build backend applications and APIs.
  • Install Express and the MongoDB driver with npm install express mongodb.
  • MongoClient connects Node.js/Express.js applications to MongoDB.
  • app.get() creates GET routes.
  • app.post() creates POST routes.
  • app.put() creates PUT routes.
  • app.delete() creates DELETE routes.
  • express.json() allows Express.js to process JSON request bodies.
  • req.body contains JSON data sent by the client.
  • req.params reads values from URL parameters.
  • MongoDB’s insertOne(), find(), findOne(), updateOne(), and deleteOne() can be used inside Express routes.
  • res.json() sends JSON responses to the client.
  • Express.js and MongoDB together can be used to create REST APIs.

FAQs

1. What is MongoDB with Express.js?

MongoDB with Express.js means using MongoDB as the database and Express.js as the Node.js web framework for handling HTTP requests and API routes.

2. Which package connects Express.js to MongoDB?

The official MongoDB Node.js driver is installed using:

npm install mongodb

Express.js itself is installed using:

npm install express

3. Why is express.json() used?

express.json() is middleware that allows Express.js to parse incoming JSON request bodies.

For example:

app.use(express.json());

allows you to access submitted JSON through:

req.body

4. How do I create a GET API with MongoDB?

Use an Express GET route and MongoDB’s find() method:

app.get("/students", async (req, res) => {
    const result = await students.find({}).toArray();
    res.json(result);
});

5. How do I insert data into MongoDB from Express.js?

Use a POST route with insertOne():

app.post("/students", async (req, res) => {
    const result = await students.insertOne(req.body);
    res.json(result);
});

6. Can Express.js perform MongoDB CRUD operations?

Yes. An Express.js application can call MongoDB driver methods such as:

Create → insertOne()
Read   → find() / findOne()
Update → updateOne()
Delete → deleteOne()

7. Is Express.js a database?

No. Express.js is a Node.js web framework, not a database.

MongoDB is the database in this setup:

Express.js → Backend/API
MongoDB    → Database
Node.js    → Runtime

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top