Node.js Database Integration Practice Questions with Solutions

Introduction

Database integration allows a Node.js application to store, retrieve, update, and delete data permanently. Node.js can work with databases such as MongoDB, MySQL, PostgreSQL, and SQLite. In this chapter, you will practice database integration from the basics, including database connections, queries, inserting records, reading data, updating records, deleting records, error handling, and connecting database logic with Express.js APIs. Node.js Database Integration practice questions with solutions help to understand the concepts.

Question 1: How do you connect Node.js with MongoDB?

Problem

Create a basic Node.js application that connects to MongoDB using Mongoose.

Solution

First create a project:

mkdir database-app
cd database-app
npm init -y

Install Mongoose:

npm install mongoose

Create app.js:

const mongoose = require("mongoose");

const mongoURL =
    "mongodb://127.0.0.1:27017/studentDB";

mongoose
    .connect(mongoURL)
    .then(() => {

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

    })
    .catch(error => {

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

    });

Step-by-Step Explanation

Import Mongoose:

const mongoose = require("mongoose");

Create the MongoDB connection URL:

const mongoURL =
    "mongodb://127.0.0.1:27017/studentDB";

Connect using:

mongoose.connect(mongoURL)

If the connection succeeds:

.then(() => {
    console.log("MongoDB connected successfully.");
})

If something goes wrong:

.catch(error => {
    console.error(error);
})

Expected Output

MongoDB connected successfully.

Important Point

The database name in this example is:

studentDB

If the database does not already exist, MongoDB can create it when data is stored.


Question 2: How do you create a MongoDB Model in Node.js?

Problem

Create a Student model with:

  • Name
  • Age
  • Course

Solution

Create:

models/Student.js

Add:

const mongoose =
    require("mongoose");

const studentSchema =
    new mongoose.Schema({

        name: {
            type: String,
            required: true
        },

        age: {
            type: Number,
            required: true
        },

        course: {
            type: String,
            required: true
        }

    });

const Student =
    mongoose.model(
        "Student",
        studentSchema
    );

module.exports =
    Student;

Step-by-Step Explanation

First import Mongoose:

const mongoose =
    require("mongoose");

Create a schema:

const studentSchema =
    new mongoose.Schema({
        ...
    });

The schema defines the structure of the data.

For example:

name: {
    type: String,
    required: true
}

means the name should be a string and is required.

Finally create the Model:

const Student =
    mongoose.model(
        "Student",
        studentSchema
    );

Question 3: How do you insert a document into MongoDB using Node.js?

Problem

Insert a student into MongoDB using the Student Model.

Solution

Assume the Student Model from Question 2 already exists.

Create app.js:

const mongoose =
    require("mongoose");

const Student =
    require("./models/Student");

async function startApp() {

    try {

        await mongoose.connect(
            "mongodb://127.0.0.1:27017/studentDB"
        );

        console.log(
            "MongoDB connected."
        );

        const student =
            await Student.create({

                name: "Rahul",

                age: 20,

                course: "Node.js"

            });

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

    } catch (error) {

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

    }

}

startApp();

Expected Result

MongoDB will store a document similar to:

{
    "_id": "generated-by-mongodb",
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

Step-by-Step Explanation

Connect to MongoDB:

await mongoose.connect(
    "mongodb://127.0.0.1:27017/studentDB"
);

Then create a document:

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

Mongoose sends the data to MongoDB.


Question 4: How do you read all records from MongoDB?

Problem

Retrieve all students from the database.

Solution

const mongoose =
    require("mongoose");

const Student =
    require("./models/Student");

async function getStudents() {

    try {

        await mongoose.connect(
            "mongodb://127.0.0.1:27017/studentDB"
        );

        const students =
            await Student.find();

        console.log(
            students
        );

    } catch (error) {

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

    }

}

getStudents();

Step-by-Step Explanation

The important query is:

Student.find();

It asks MongoDB for the students stored in the Student collection.

The result is stored in:

const students =
    await Student.find();

Example Result

[
    {
        name: "Rahul",
        age: 20,
        course: "Node.js"
    },
    {
        name: "Priya",
        age: 19,
        course: "JavaScript"
    }
]

Important Point

find() returns an array of matching documents.


Question 5: How do you find one record from MongoDB?

Problem

Find a student whose name is "Rahul".

Solution

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

console.log(
    student
);

Complete Example

const mongoose =
    require("mongoose");

const Student =
    require("./models/Student");

async function findStudent() {

    try {

        await mongoose.connect(
            "mongodb://127.0.0.1:27017/studentDB"
        );

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

        if (!student) {

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

            return;

        }

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

    } catch (error) {

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

    }

}

findStudent();

Step-by-Step Explanation

Use:

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

Mongoose searches for a matching document.

If no document is found, the result can be null.


Question 6: How do you update a MongoDB record using Node.js?

Problem

Find Rahul’s student record and change the course to "Full Stack Development".

Solution

const updatedStudent =
    await Student.findOneAndUpdate(

        {
            name: "Rahul"
        },

        {
            course:
                "Full Stack Development"
        },

        {
            new: true
        }

    );

console.log(
    updatedStudent
);

Complete Example

const mongoose =
    require("mongoose");

const Student =
    require("./models/Student");

async function updateStudent() {

    try {

        await mongoose.connect(
            "mongodb://127.0.0.1:27017/studentDB"
        );

        const updatedStudent =
            await Student.findOneAndUpdate(

                {
                    name: "Rahul"
                },

                {
                    course:
                        "Full Stack Development"
                },

                {
                    new: true
                }

            );

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

    } catch (error) {

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

    }

}

updateStudent();

Step-by-Step Explanation

First specify which record should be updated:

{
    name: "Rahul"
}

Then specify the new value:

{
    course:
        "Full Stack Development"
}

The option:

{
    new: true
}

makes Mongoose return the updated document.


Question 7: How do you delete a MongoDB record using Node.js?

Problem

Delete the student whose name is "Rahul".

Solution

const deletedStudent =
    await Student.findOneAndDelete({

        name: "Rahul"

    });

console.log(
    deletedStudent
);

Complete Example

const mongoose =
    require("mongoose");

const Student =
    require("./models/Student");

async function deleteStudent() {

    try {

        await mongoose.connect(
            "mongodb://127.0.0.1:27017/studentDB"
        );

        const deletedStudent =
            await Student.findOneAndDelete({

                name: "Rahul"

            });

        if (!deletedStudent) {

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

            return;

        }

        console.log(
            "Student deleted:",
            deletedStudent
        );

    } catch (error) {

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

    }

}

deleteStudent();

Step-by-Step Explanation

The query:

Student.findOneAndDelete({
    name: "Rahul"
});

searches for the matching document and deletes it.


Question 8: How do you connect a database with an Express.js API?

Problem

Create an Express.js API that connects to MongoDB and returns all students.

Solution

Install the required packages:

npm install express mongoose

Create app.js:

const express =
    require("express");

const mongoose =
    require("mongoose");

const Student =
    require("./models/Student");

const app =
    express();

app.use(
    express.json()
);


mongoose
    .connect(
        "mongodb://127.0.0.1:27017/studentDB"
    )
    .then(() => {

        console.log(
            "MongoDB connected."
        );

        app.listen(
            3000,
            () => {

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

            }
        );

    })
    .catch(error => {

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

    });


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

        try {

            const students =
                await Student.find();

            res.json({

                success: true,

                students:
                    students

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to fetch students."

            });

        }

    }
);

Test the API

Open:

http://localhost:3000/students

Example Response

{
    "success": true,
    "students": [
        {
            "name": "Rahul",
            "age": 20,
            "course": "Node.js"
        },
        {
            "name": "Priya",
            "age": 19,
            "course": "JavaScript"
        }
    ]
}

Step-by-Step Explanation

The application connects to MongoDB:

mongoose.connect(...)

Express starts after the database connection succeeds.

The API route:

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

retrieves the students using:

await Student.find();

Question 9: How do you store the database connection in a separate file?

Problem

Move the MongoDB connection logic into a separate file so that app.js stays clean.

Solution

Create:

config/
└── database.js

Add:

const mongoose =
    require("mongoose");

async function connectDatabase() {

    try {

        await mongoose.connect(
            "mongodb://127.0.0.1:27017/studentDB"
        );

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

    } catch (error) {

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

        throw error;

    }

}

module.exports =
    connectDatabase;

Now update app.js:

const express =
    require("express");

const connectDatabase =
    require("./config/database");

const app =
    express();

app.use(
    express.json()
);

async function startServer() {

    try {

        await connectDatabase();

        app.listen(
            3000,
            () => {

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

            }
        );

    } catch (error) {

        console.error(
            "Application startup failed."
        );

    }

}

startServer();

Project Structure

database-app/
│
├── config/
│   └── database.js
│
├── models/
│   └── Student.js
│
├── app.js
└── package.json

Step-by-Step Explanation

The database connection is now separated from the main application.

database.js handles:

Database Connection

app.js handles:

Express Application
Server Startup

Important Point

Separating database configuration makes the project easier to maintain as it grows.


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

Problem

Create a simple Express.js API using MongoDB and Mongoose that supports:

POST   /students
GET    /students
GET    /students/:id
PUT    /students/:id
DELETE /students/:id

Solution

Step 1: Install Packages

npm init -y
npm install express mongoose

Step 2: Create the Model

Create:

models/Student.js

Add:

const mongoose =
    require("mongoose");

const studentSchema =
    new mongoose.Schema({

        name: {
            type: String,
            required: true,
            trim: true
        },

        age: {
            type: Number,
            required: true
        },

        course: {
            type: String,
            required: true,
            trim: true
        }

    });

const Student =
    mongoose.model(
        "Student",
        studentSchema
    );

module.exports =
    Student;

Step 3: Create the Express Application

Create app.js:

const express =
    require("express");

const mongoose =
    require("mongoose");

const Student =
    require("./models/Student");

const app =
    express();

app.use(
    express.json()
);


mongoose
    .connect(
        "mongodb://127.0.0.1:27017/studentDB"
    )
    .then(() => {

        console.log(
            "MongoDB connected."
        );

        app.listen(
            3000,
            () => {

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

            }
        );

    })
    .catch(error => {

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

    });

Step 4: Create POST API

Add:

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

        try {

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

            if (
                !name ||
                age === undefined ||
                !course
            ) {

                return res.status(400).json({

                    success: false,

                    message:
                        "Name, age and course are required."

                });

            }

            const student =
                await Student.create({

                    name:
                        name,

                    age:
                        age,

                    course:
                        course

                });

            res.status(201).json({

                success: true,

                student:
                    student

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to create student."

            });

        }

    }
);

Test POST

POST http://localhost:3000/students

JSON:

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

Step 5: Create GET All Students API

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

        try {

            const students =
                await Student.find();

            res.json({

                success: true,

                students:
                    students

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to fetch students."

            });

        }

    }
);

Test:

GET http://localhost:3000/students

Step 6: Create GET One Student API

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

        try {

            const student =
                await Student.findById(
                    req.params.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."

            });

        }

    }
);

Test:

GET http://localhost:3000/students/ID

Replace ID with the student’s MongoDB _id.


Step 7: Create PUT API

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

        try {

            const student =
                await Student.findByIdAndUpdate(

                    req.params.id,

                    req.body,

                    {
                        new: true,
                        runValidators: true
                    }

                );

            if (!student) {

                return res.status(404).json({

                    success: false,

                    message:
                        "Student not found."

                });

            }

            res.json({

                success: true,

                message:
                    "Student updated successfully.",

                student:
                    student

            });

        } catch (error) {

            res.status(500).json({

                success: false,

                message:
                    "Unable to update student."

            });

        }

    }
);

Test PUT

PUT http://localhost:3000/students/ID

JSON:

{
    "course": "Full Stack Development"
}

The student record is updated.

Important Point

The option:

runValidators: true

asks Mongoose to apply schema validators during this update operation.


Step 8: Create DELETE API

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

        try {

            const student =
                await Student.findByIdAndDelete(
                    req.params.id
                );

            if (!student) {

                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."

            });

        }

    }
);

Test DELETE

DELETE http://localhost:3000/students/ID

Complete API Structure

Node.js Application
        ↓
    Express.js
        ↓
      Routes
        ↓
     Mongoose
        ↓
     MongoDB

CRUD Summary

CREATE
POST /students

READ
GET /students
GET /students/:id

UPDATE
PUT /students/:id

DELETE
DELETE /students/:id

Important Point

This example gives you the basic structure of a database-backed Node.js API. In a production application, you should additionally separate routes, controllers, models, database configuration, validation, authentication, and error handling.

Key Takeaways

1. Node.js can work with many databases

Popular choices include MongoDB, MySQL, PostgreSQL, and SQLite.

2. Mongoose is commonly used with MongoDB

Mongoose provides schemas, models, queries, validation, and other features for working with MongoDB from Node.js.

3. A database connection is required

For MongoDB with Mongoose:

await mongoose.connect(
    "mongodb://127.0.0.1:27017/studentDB"
);

4. A Schema defines document structure

Example:

const studentSchema =
    new mongoose.Schema({
        name: String,
        age: Number
    });

5. A Model works with database documents

Example:

const Student =
    mongoose.model(
        "Student",
        studentSchema
    );

6. create() inserts data

await Student.create({
    name: "Rahul",
    age: 20
});

7. find() retrieves multiple documents

const students =
    await Student.find();

8. findOne() retrieves one matching document

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

9. findById() searches using _id

const student =
    await Student.findById(id);

10. findOneAndUpdate() updates a matching document

await Student.findOneAndUpdate(
    { name: "Rahul" },
    { age: 21 }
);

11. findByIdAndUpdate() updates by ID

await Student.findByIdAndUpdate(
    id,
    data,
    {
        new: true
    }
);

12. findOneAndDelete() deletes a matching document

await Student.findOneAndDelete({
    name: "Rahul"
});

13. findByIdAndDelete() deletes by ID

await Student.findByIdAndDelete(
    id
);

14. Use async/await for database operations

Database operations are asynchronous, so async/await makes the code easier to read.

15. Handle database errors

Use try...catch around asynchronous database operations.

16. Keep database configuration separate

A separate database.js file can keep connection logic out of app.js.

17. Express and databases work together

Express handles HTTP requests while the database stores application data.

18. CRUD is the foundation of database applications

CRUD means:

Create
Read
Update
Delete

19. Validate data before storing it

Do not blindly save client-provided data to your database.

20. Do not expose database credentials

Production applications should keep database credentials outside source code, commonly through environment variables.

FAQs

1. What is database integration in Node.js?

Database integration means connecting a Node.js application to a database so the application can store, retrieve, update, and delete data.

For example, a Node.js application can connect to MongoDB and store user or student records.

2. Which databases can be used with Node.js?

Node.js can work with many databases, including:

  • MongoDB
  • MySQL
  • PostgreSQL
  • SQLite
  • MariaDB
  • Microsoft SQL Server

The appropriate database depends on the application’s requirements.

3. What is Mongoose in Node.js?

Mongoose is an ODM library commonly used to work with MongoDB in Node.js applications.

It provides features such as:

  • Schemas
  • Models
  • Validation
  • Queries
  • Middleware

4. What is the difference between a MongoDB Schema and Model?

A Schema describes the structure and rules for documents.

A Model is created from the Schema and provides methods for interacting with the MongoDB collection.

For example:

const studentSchema =
    new mongoose.Schema({
        name: String
    });

const Student =
    mongoose.model(
        "Student",
        studentSchema
    );

5. How do I connect MongoDB to Node.js?

Using Mongoose, you can connect with:

const mongoose =
    require("mongoose");

mongoose.connect(
    "mongodb://127.0.0.1:27017/studentDB"
);

For production applications, the connection string should normally come from an environment variable rather than being hard-coded.

6. How do I insert data into MongoDB using Node.js?

Using a Mongoose Model:

const student =
    await Student.create({
        name: "Rahul",
        age: 20,
        course: "Node.js"
    });

The created document is returned by the operation.

7. Why should I use a separate database connection file?

Separating the connection logic makes the application easier to organize and maintain.

For example:

config/
└── database.js

can contain the MongoDB connection code, while app.js handles the Express application and server startup.

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

Scroll to Top