Node.js CRUD Operations Practice Questions with Solutions

Introduction

CRUD stands for Create, Read, Update, and Delete. These four operations are the foundation of most database applications. In Node.js, CRUD operations are commonly used with MongoDB to create, retrieve, modify, and remove data. In this chapter, you will practice 10 solved CRUD questions, starting with simple operations and gradually building a complete student management API using Node.js, Express.js, and MongoDB. Node.js CRUD Operations practice questions with solutions help to understand the concepts.

Question 1: How do you create a document using Node.js and MongoDB?

Problem

Create a Node.js program that adds one student to a MongoDB collection.

Solution

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

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

const client = new MongoClient(uri);

async function createStudent() {

    try {

        await client.connect();

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

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

        const student = {

            name: "Rahul",
            age: 20,
            course: "Node.js"

        };

        const result =
            await students.insertOne(student);

        console.log(
            "Student created successfully."
        );

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

    } catch (error) {

        console.error(
            "Error:",
            error.message
        );

    } finally {

        await client.close();

    }

}

createStudent();

Output

Student created successfully.
Student ID: ObjectId(...)

Step-by-Step Explanation

First, connect to MongoDB:

await client.connect();

Select the database:

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

Select the collection:

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

Create a JavaScript object:

const student = {
    name: "Rahul",
    age: 20,
    course: "Node.js"
};

Finally, insert it:

await students.insertOne(student);

CRUD Operation

C = Create

Question 2: How do you create multiple documents using Node.js?

Problem

Insert three students into MongoDB using one operation.

Solution

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

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

const client = new MongoClient(uri);

async function createStudents() {

    try {

        await client.connect();

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

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

        const data = [

            {
                name: "Rahul",
                age: 20,
                course: "Node.js"
            },

            {
                name: "Priya",
                age: 19,
                course: "Python"
            },

            {
                name: "Aman",
                age: 21,
                course: "JavaScript"
            }

        ];

        const result =
            await students.insertMany(data);

        console.log(
            result.insertedCount +
            " students created."
        );

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

createStudents();

Output

3 students created.

Step-by-Step Explanation

Create an array:

const data = [
    {
        name: "Rahul",
        age: 20,
        course: "Node.js"
    },
    {
        name: "Priya",
        age: 19,
        course: "Python"
    },
    {
        name: "Aman",
        age: 21,
        course: "JavaScript"
    }
];

Then use:

await students.insertMany(data);

MongoDB inserts all three documents.

CRUD Operation

C = Create

Question 3: How do you read all documents from MongoDB?

Problem

Retrieve all students from the students collection.

Solution

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

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

const client = new MongoClient(uri);

async function getStudents() {

    try {

        await client.connect();

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

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

        const data =
            await students
                .find({})
                .toArray();

        console.log(data);

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

getStudents();

Example Output

[
    {
        _id: ObjectId(...),
        name: "Rahul",
        age: 20,
        course: "Node.js"
    },
    {
        _id: ObjectId(...),
        name: "Priya",
        age: 19,
        course: "Python"
    }
]

Step-by-Step Explanation

The find() method searches for documents:

students.find({})

The empty object means:

Find all documents.

Then:

.toArray()

converts the MongoDB cursor into an array.

CRUD Operation

R = Read

Question 4: How do you read one document from MongoDB?

Problem

Find one student whose name is Rahul.

Solution

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

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

const client = new MongoClient(uri);

async function getStudent() {

    try {

        await client.connect();

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

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

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

        if (student) {

            console.log(
                "Student found:"
            );

            console.log(student);

        } else {

            console.log(
                "Student not found."
            );

        }

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

getStudent();

Output

If Rahul exists:

Student found:
{
    _id: ObjectId(...),
    name: "Rahul",
    age: 20,
    course: "Node.js"
}

If Rahul does not exist:

Student not found.

Step-by-Step Explanation

The search condition is:

{
    name: "Rahul"
}

MongoDB searches for one matching document:

students.findOne({
    name: "Rahul"
});

CRUD Operation

R = Read

Question 5: How do you update a document in MongoDB?

Problem

Change Rahul’s course from Node.js to MongoDB.

Solution

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

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

const client = new MongoClient(uri);

async function updateStudent() {

    try {

        await client.connect();

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

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

        const result =
            await students.updateOne(

                {
                    name: "Rahul"
                },

                {
                    $set: {
                        course: "MongoDB"
                    }
                }

            );

        if (result.modifiedCount === 1) {

            console.log(
                "Student updated successfully."
            );

        } else {

            console.log(
                "Student was not updated."
            );

        }

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

updateStudent();

Before Update

{
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

After Update

{
    "name": "Rahul",
    "age": 20,
    "course": "MongoDB"
}

Step-by-Step Explanation

The first object identifies the document:

{
    name: "Rahul"
}

The second object contains the update:

{
    $set: {
        course: "MongoDB"
    }
}

$set changes only the specified field.

CRUD Operation

U = Update

Question 6: How do you update multiple documents?

Problem

Change the course of all students currently studying Node.js to Advanced Node.js.

Solution

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

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

const client = new MongoClient(uri);

async function updateStudents() {

    try {

        await client.connect();

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

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

        const result =
            await students.updateMany(

                {
                    course: "Node.js"
                },

                {
                    $set: {
                        course: "Advanced Node.js"
                    }
                }

            );

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

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

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

updateStudents();

Example Output

Matched: 3
Modified: 3

Step-by-Step Explanation

updateMany() finds all documents matching:

{
    course: "Node.js"
}

Then $set changes the course:

{
    $set: {
        course: "Advanced Node.js"
    }
}

CRUD Operation

U = Update

Question 7: How do you delete one document from MongoDB?

Problem

Delete the student named Aman.

Solution

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

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

const client = new MongoClient(uri);

async function deleteStudent() {

    try {

        await client.connect();

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

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

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

        if (result.deletedCount === 1) {

            console.log(
                "Student deleted successfully."
            );

        } else {

            console.log(
                "Student not found."
            );

        }

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

deleteStudent();

Output

Student deleted successfully.

Step-by-Step Explanation

The filter identifies the student:

{
    name: "Aman"
}

Then:

students.deleteOne({
    name: "Aman"
});

deletes the matching document.

CRUD Operation

D = Delete

Question 8: How do you delete multiple documents?

Problem

Delete all students whose course is Old Course.

Solution

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

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

const client = new MongoClient(uri);

async function deleteStudents() {

    try {

        await client.connect();

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

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

        const result =
            await students.deleteMany({

                course: "Old Course"

            });

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

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

deleteStudents();

Example Output

Deleted: 4

Step-by-Step Explanation

The filter is:

{
    course: "Old Course"
}

MongoDB searches for every document matching this condition.

Then:

deleteMany()

removes all matching documents.

CRUD Operation

D = Delete

Important Point

Never use deleteMany({}) unless you intentionally want to delete all documents in the collection.


Question 9: How do you create a CRUD API using Express and MongoDB?

Problem

Create an API with four basic operations:

  • Create student
  • Read students
  • Update student
  • Delete student

Solution

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;


// Connect to MongoDB

async function connectDatabase() {

    await client.connect();

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

    students =
        db.collection("students");

    console.log(
        "MongoDB connected."
    );

}


// CREATE

app.post("/students", async (req, res) => {

    try {

        const {
            name,
            age,
            course
        } = req.body;

        if (!name || !course) {

            return res.status(400).json({

                success: false,

                message:
                    "Name and course are required."

            });

        }

        const student = {

            name: name,

            age: age,

            course: course

        };

        const result =
            await students.insertOne(
                student
            );

        res.status(201).json({

            success: true,

            message:
                "Student created.",

            id: result.insertedId

        });

    } catch (error) {

        res.status(500).json({

            success: false,

            message:
                "Unable to create student."

        });

    }

});


// READ

app.get("/students", async (req, res) => {

    try {

        const data =
            await students
                .find({})
                .toArray();

        res.json({

            success: true,

            students: data

        });

    } catch (error) {

        res.status(500).json({

            success: false,

            message:
                "Unable to get students."

        });

    }

});


// UPDATE

app.put(
    "/students/:id",
    async (req, res) => {

        try {

            const id =
                Number(req.params.id);

            const {
                course
            } = req.body;

            const result =
                await students.updateOne(

                    {
                        studentId: id
                    },

                    {
                        $set: {
                            course: course
                        }
                    }

                );

            if (
                result.modifiedCount === 0
            ) {

                return res.status(404).json({

                    success: false,

                    message:
                        "Student not found."

                });

            }

            res.json({

                success: true,

                message:
                    "Student updated."

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to update student."

            });

        }

    }
);


// DELETE

app.delete(
    "/students/:id",
    async (req, res) => {

        try {

            const id =
                Number(req.params.id);

            const result =
                await students.deleteOne({

                    studentId: id

                });

            if (
                result.deletedCount === 0
            ) {

                return res.status(404).json({

                    success: false,

                    message:
                        "Student not found."

                });

            }

            res.json({

                success: true,

                message:
                    "Student deleted."

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to delete student."

            });

        }

    }
);


// Start server

async function startServer() {

    try {

        await connectDatabase();

        app.listen(3000, () => {

            console.log(
                "Server running on port 3000"
            );

        });

    } catch (error) {

        console.error(
            error.message
        );

    }

}

startServer();

Important Note

For the PUT and DELETE routes above, documents should contain a numeric studentId. For example:

{
    "studentId": 1,
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

Test CREATE

Send:

POST http://localhost:3000/students

Body:

{
    "studentId": 1,
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

Test READ

GET http://localhost:3000/students

Test UPDATE

PUT http://localhost:3000/students/1

Body:

{
    "course": "MongoDB"
}

Test DELETE

DELETE http://localhost:3000/students/1

CRUD Flow

POST    → CREATE
GET     → READ
PUT     → UPDATE
DELETE  → DELETE

Question 10: How do you build a complete Node.js CRUD application?

Problem

Build a beginner-friendly student management API using Node.js, Express.js, and MongoDB with all four CRUD operations.

Solution

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;


// MongoDB connection

async function connectDatabase() {

    await client.connect();

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

    students =
        db.collection("students");

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

}


// CREATE

app.post("/students", async (req, res) => {

    try {

        const {
            studentId,
            name,
            age,
            course
        } = req.body;

        if (
            !studentId ||
            !name ||
            !age ||
            !course
        ) {

            return res.status(400).json({

                success: false,

                message:
                    "All student fields are required."

            });

        }

        const existingStudent =
            await students.findOne({
                studentId: Number(studentId)
            });

        if (existingStudent) {

            return res.status(409).json({

                success: false,

                message:
                    "Student ID already exists."

            });

        }

        const student = {

            studentId:
                Number(studentId),

            name: name,

            age: Number(age),

            course: course

        };

        await students.insertOne(
            student
        );

        res.status(201).json({

            success: true,

            message:
                "Student created successfully.",

            student: student

        });

    } catch (error) {

        console.error(
            error.message
        );

        res.status(500).json({

            success: false,

            message:
                "Internal server error."

        });

    }

});


// READ ALL

app.get("/students", async (req, res) => {

    try {

        const data =
            await students
                .find({})
                .toArray();

        res.json({

            success: true,

            count: data.length,

            students: data

        });

    } catch (error) {

        res.status(500).json({

            success: false,

            message:
                "Unable to fetch students."

        });

    }

});


// READ ONE

app.get(
    "/students/:id",
    async (req, res) => {

        try {

            const id =
                Number(req.params.id);

            const student =
                await students.findOne({

                    studentId: id

                });

            if (!student) {

                return res.status(404).json({

                    success: false,

                    message:
                        "Student not found."

                });

            }

            res.json({

                success: true,

                student: student

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to fetch student."

            });

        }

    }
);


// UPDATE

app.put(
    "/students/:id",
    async (req, res) => {

        try {

            const id =
                Number(req.params.id);

            const {
                name,
                age,
                course
            } = req.body;

            const updateData = {};

            if (name) {

                updateData.name =
                    name;

            }

            if (age) {

                updateData.age =
                    Number(age);

            }

            if (course) {

                updateData.course =
                    course;

            }

            if (
                Object.keys(updateData)
                    .length === 0
            ) {

                return res.status(400).json({

                    success: false,

                    message:
                        "Provide data to update."

                });

            }

            const result =
                await students.updateOne(

                    {
                        studentId: id
                    },

                    {
                        $set: updateData
                    }

                );

            if (
                result.matchedCount === 0
            ) {

                return res.status(404).json({

                    success: false,

                    message:
                        "Student not found."

                });

            }

            res.json({

                success: true,

                message:
                    "Student updated successfully."

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to update student."

            });

        }

    }
);


// DELETE

app.delete(
    "/students/:id",
    async (req, res) => {

        try {

            const id =
                Number(req.params.id);

            const result =
                await students.deleteOne({

                    studentId: id

                });

            if (
                result.deletedCount === 0
            ) {

                return res.status(404).json({

                    success: false,

                    message:
                        "Student not found."

                });

            }

            res.json({

                success: true,

                message:
                    "Student deleted successfully."

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to delete student."

            });

        }

    }
);


// Start server

async function startServer() {

    try {

        await connectDatabase();

        app.listen(3000, () => {

            console.log(
                "Server running at http://localhost:3000"
            );

        });

    } catch (error) {

        console.error(
            "Failed to start server:",
            error.message
        );

    }

}

startServer();

Step 1: Install Packages

Create a project:

npm init -y

Install Express and MongoDB:

npm install express mongodb

Step 2: Start MongoDB

Make sure your local MongoDB server is running.

The example uses:

mongodb://127.0.0.1:27017

Step 3: Run the Application

Save the code as:

index.js

Then run:

node index.js

You should see:

MongoDB connected successfully.
Server running at http://localhost:3000

Step 4: Test CREATE

Use:

POST /students

Body:

{
    "studentId": 1,
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

Response:

{
    "success": true,
    "message": "Student created successfully.",
    "student": {
        "studentId": 1,
        "name": "Rahul",
        "age": 20,
        "course": "Node.js"
    }
}

Step 5: Test READ ALL

Use:

GET /students

Example response:

{
    "success": true,
    "count": 1,
    "students": [
        {
            "studentId": 1,
            "name": "Rahul",
            "age": 20,
            "course": "Node.js"
        }
    ]
}

Step 6: Test READ ONE

Use:

GET /students/1

Response:

{
    "success": true,
    "student": {
        "studentId": 1,
        "name": "Rahul",
        "age": 20,
        "course": "Node.js"
    }
}

Step 7: Test UPDATE

Use:

PUT /students/1

Body:

{
    "course": "MongoDB"
}

Response:

{
    "success": true,
    "message": "Student updated successfully."
}

The student’s course is now:

MongoDB

Step 8: Test DELETE

Use:

DELETE /students/1

Response:

{
    "success": true,
    "message": "Student deleted successfully."
}

Complete CRUD Structure

                 Node.js Application
                         |
                     Express.js
                         |
        +----------------+----------------+
        |                |                |
      CREATE            READ            UPDATE
        |                |                |
      POST              GET              PUT
        |                |                |
        +----------------+----------------+
                         |
                       DELETE
                         |
                       DELETE
                         |
                      MongoDB

CRUD Summary

OperationHTTP MethodMongoDB Method
CreatePOSTinsertOne()
ReadGETfind() / findOne()
UpdatePUTupdateOne()
DeleteDELETEdeleteOne()

Key Takeaways

  • CRUD means Create, Read, Update, and Delete.
  • CRUD operations are the foundation of many database applications.
  • Node.js can perform CRUD operations with MongoDB using the MongoDB driver.
  • insertOne() creates one document.
  • insertMany() creates multiple documents.
  • find() retrieves multiple documents.
  • findOne() retrieves one document.
  • updateOne() updates one document.
  • updateMany() updates multiple documents.
  • deleteOne() deletes one document.
  • deleteMany() deletes multiple documents.
  • $set is commonly used to update specific fields.
  • insertedId contains the ID generated for an inserted document.
  • insertedCount tells you how many documents were inserted.
  • matchedCount tells you how many documents matched an update filter.
  • modifiedCount tells you how many documents were changed.
  • deletedCount tells you how many documents were deleted.
  • Express.js can be combined with MongoDB to create CRUD APIs.
  • POST is commonly used for creating resources.
  • GET is commonly used for reading resources.
  • PUT is commonly used for updating resources.
  • DELETE is commonly used for deleting resources.
  • Route parameters such as /students/:id can identify individual records.
  • req.params reads values from route parameters.
  • req.body reads data sent in a JSON request body when express.json() is enabled.
  • HTTP status 201 can indicate that a resource was successfully created.
  • HTTP status 400 can indicate invalid input.
  • HTTP status 404 can indicate that a resource was not found.
  • HTTP status 409 can indicate a conflict such as a duplicate ID.
  • HTTP status 500 can indicate an unexpected server-side error.
  • Always validate user input before storing it in the database.
  • Be careful when using updateMany() and deleteMany().
  • Avoid exposing sensitive database errors directly to API users.
  • Database connection strings should normally be stored securely using environment variables in real applications.
  • CRUD knowledge is essential for building REST APIs and full-stack applications.

FAQs

1. What does CRUD mean in Node.js?

CRUD stands for:

C → Create
R → Read
U → Update
D → Delete

These operations allow an application to create, retrieve, modify, and remove database data.

2. How do you create data in MongoDB using Node.js?

Use insertOne():

await students.insertOne({
    name: "Rahul",
    age: 20,
    course: "Node.js"
});

For multiple documents, you can use insertMany().

3. How do you read data from MongoDB using Node.js?

Use find() for multiple documents:

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

Use findOne() when you need one matching document:

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

4. How do you update data in MongoDB using Node.js?

Use updateOne() with $set:

await collection.updateOne(

    {
        name: "Rahul"
    },

    {
        $set: {
            course: "MongoDB"
        }
    }

);

The first object identifies the document and the second object contains the update.

5. How do you delete data from MongoDB using Node.js?

Use deleteOne():

await collection.deleteOne({
    name: "Rahul"
});

For multiple matching documents, use:

await collection.deleteMany({
    course: "Old Course"
});

6. What are the HTTP methods used for CRUD APIs?

The commonly used HTTP methods are:

POST    → Create
GET     → Read
PUT     → Update
DELETE  → Delete

For example:

POST   /students
GET    /students
PUT    /students/1
DELETE /students/1

7. Why are CRUD operations important in Node.js?

CRUD operations are important because most applications need to store and manage data.

For example, a student application might need to:

Create → Add a student
Read   → Display students
Update → Change a student's course
Delete → Remove a student

Understanding CRUD gives you the foundation needed to build practical Node.js and REST API projects.

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

Scroll to Top