Paramclasses Academy - Blog

Tutorials Details

←
Post 24 of 40
→

Connect Node.js to MongoDB Using Mongoose: Step-by-Step Tutorial

Connect Node.js to MongoDB Using Mongoose: Step-by-Step Tutorial

October 30, 2026

✦ Connect Node.js to MongoDB Using Mongoose: Step-by-Step Tutorial

❖ Introduction

Node.js is a popular JavaScript runtime used to build backend applications, REST APIs, and full-stack web applications. To store application data permanently, Node.js needs a database. One popular choice is MongoDB, a NoSQL database that stores information in flexible, JSON-like documents.

Mongoose is an Object Data Modeling (ODM) library that helps Node.js developers interact with MongoDB. It provides schemas, models, validation, and convenient methods for creating, reading, updating, and deleting documents.

In this tutorial, you will learn how to connect Node.js to MongoDB using Mongoose. You will also build a practical Student Management API that can add students, retrieve student records, and validate incoming data.

✦ 1. What Are Node.js, MongoDB, and Mongoose?

Node.js: Runs JavaScript on the server and handles application logic and HTTP requests.

MongoDB: Stores data as documents inside collections. Unlike a traditional relational database, MongoDB does not require every record to be stored in a fixed set of table columns.

Mongoose: Connects your Node.js application to MongoDB and helps define the structure and validation rules for documents.

For example, a student document might look like this:

{
  "name": "Aman Verma",
  "mobile": "9123456780",
  "course": "Node.js Backend"
}

MongoDB stores such documents inside a collection. In this tutorial, the collection will be named students.

✦ 2. Install the Required Software

Before starting, install:

  • Node.js and npm

  • MongoDB Community Server or a MongoDB Atlas account

  • Visual Studio Code

  • Postman for testing API requests

You can use MongoDB locally or use MongoDB Atlas, a cloud-hosted MongoDB service.

If MongoDB is installed locally, make sure its database service is running before starting the application.

✦ 3. Create a Node.js Project

Open your terminal and run:

mkdir node-mongodb-tutorial
cd node-mongodb-tutorial
npm init -y
npm install express mongoose dotenv

The packages serve the following purposes:

  • express creates API endpoints.

  • mongoose connects Node.js to MongoDB and manages document models.

  • dotenv loads configuration from a .env file.

Create the following project structure:

node-mongodb-tutorial/
├── server.js
├── .env
├── .gitignore
└── package.json

✦ 4. Configure the MongoDB Connection

Create a .env file in the project root.

For a local MongoDB installation, use:

PORT=3000
MONGODB_URI=mongodb://127.0.0.1:27017/student_db

Here, student_db is the database name. MongoDB will generally create the database when data is first written to it.

If you use MongoDB Atlas, replace the URI with the connection string provided by your Atlas project. Keep the username and password private, and URL-encode special characters in credentials when necessary.

Now create .gitignore:

node_modules/
.env

This helps prevent local dependencies and private connection settings from being committed to Git.

✦ 5. Connect Node.js to MongoDB Using Mongoose

Open server.js and copy this complete example.

require("dotenv").config();

const express = require("express");
const mongoose = require("mongoose");

const app = express();

app.use(express.json());

// Define the Student schema
const studentSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: [true, "Student name is required"],
            trim: true,
            maxlength: 100
        },
        mobile: {
            type: String,
            required: [true, "Mobile number is required"],
            trim: true,
            maxlength: 15
        },
        course: {
            type: String,
            required: [true, "Course name is required"],
            trim: true,
            maxlength: 100
        }
    },
    {
        timestamps: true
    }
);

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

// API home and connection status
app.get("/", (req, res) => {
    res.json({
        success: true,
        message: "Node.js and MongoDB API is running",
        databaseState: mongoose.connection.readyState
    });
});

// Get all students
app.get("/students", async (req, res) => {
    try {
        const students = await Student.find().sort({ createdAt: -1 });

        res.json({
            success: true,
            data: students
        });
    } catch (error) {
        console.error("Fetch error:", error.message);

        res.status(500).json({
            success: false,
            message: "Unable to fetch students"
        });
    }
});

// Get a student by MongoDB document ID
app.get("/students/:id", async (req, res) => {
    if (!mongoose.isValidObjectId(req.params.id)) {
        return res.status(400).json({
            success: false,
            message: "Invalid student ID"
        });
    }

    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,
            data: student
        });
    } catch (error) {
        console.error("Find error:", error.message);

        res.status(500).json({
            success: false,
            message: "Unable to retrieve student"
        });
    }
});

// Add a student
app.post("/students", async (req, res) => {
    const { name, mobile, course } = req.body;

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

    try {
        const student = await Student.create({
            name,
            mobile,
            course
        });

        res.status(201).json({
            success: true,
            message: "Student added successfully",
            data: student
        });
    } catch (error) {
        if (error.name === "ValidationError") {
            return res.status(400).json({
                success: false,
                message: error.message
            });
        }

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

        res.status(500).json({
            success: false,
            message: "Unable to save student"
        });
    }
});

// Update a student
app.put("/students/:id", async (req, res) => {
    if (!mongoose.isValidObjectId(req.params.id)) {
        return res.status(400).json({
            success: false,
            message: "Invalid student ID"
        });
    }

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

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

    try {
        const student = await Student.findByIdAndUpdate(
            req.params.id,
            {
                name: name.trim(),
                mobile: mobile.trim(),
                course: course.trim()
            },
            {
                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",
            data: student
        });
    } catch (error) {
        if (error.name === "ValidationError") {
            return res.status(400).json({
                success: false,
                message: error.message
            });
        }

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

        res.status(500).json({
            success: false,
            message: "Unable to update student"
        });
    }
});

// Delete a student
app.delete("/students/:id", async (req, res) => {
    if (!mongoose.isValidObjectId(req.params.id)) {
        return res.status(400).json({
            success: false,
            message: "Invalid student ID"
        });
    }

    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) {
        console.error("Delete error:", error.message);

        res.status(500).json({
            success: false,
            message: "Unable to delete student"
        });
    }
});

// Connect to MongoDB before starting the server
async function startServer() {
    try {
        if (!process.env.MONGODB_URI) {
            throw new Error("MONGODB_URI is missing from .env");
        }

        await mongoose.connect(process.env.MONGODB_URI);

        console.log("MongoDB connected successfully");

        const port = Number(process.env.PORT || 3000);

        app.listen(port, () => {
            console.log(`Server running at http://localhost:${port}`);
        });
    } catch (error) {
        console.error("Application startup failed:", error.message);
        process.exitCode = 1;
    }
}

startServer();

This code includes all four basic CRUD operations: create, read, update, and delete.

✦ 6. Understand Schema and Model

A schema defines the fields, data types, and validation rules for documents.

const studentSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    course: {
        type: String,
        required: true
    }
});

A model is created from the schema:

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

You can use this model to interact with MongoDB:

const students = await Student.find();

Mongoose normally maps the Student model to a collection named students. MongoDB documents also have an _id field, which Mongoose uses to identify records.

✦ 7. Start the Application

Run the following command:

node server.js

If the connection succeeds, the terminal should show:

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

Open http://localhost:3000/ in your browser to check the API status.

The database state returned by Mongoose is normally 1 when the connection is connected.

✦ 8. Test the API in Postman

❖ Add a Student

  • Method: POST

  • URL: http://localhost:3000/students

  • Select Body → raw → JSON

Send this request:

{
    "name": "Aman Verma",
    "mobile": "9123456780",
    "course": "Node.js Backend"
}

You should receive a successful response containing the saved student document and its MongoDB _id.

❖ Get All Students

  • Method: GET

  • URL: http://localhost:3000/students

This endpoint returns the saved student records.

❖ Get One Student

  • Method: GET

  • URL: http://localhost:3000/students/YOUR_DOCUMENT_ID

Replace YOUR_DOCUMENT_ID with the _id returned when you created a student.

❖ Update a Student

  • Method: PUT

  • URL: http://localhost:3000/students/YOUR_DOCUMENT_ID

Send all three required fields in the JSON body:

{
    "name": "Aman Verma",
    "mobile": "9123456780",
    "course": "Full Stack Development"
}

❖ Delete a Student

  • Method: DELETE

  • URL: http://localhost:3000/students/YOUR_DOCUMENT_ID

Use an existing document ID. The API will return a success message if the record is deleted.

✦ 9. Common Connection Errors

❖ MongoDB connection refused

The local MongoDB service may not be running, or the host and port may be wrong. Check your MongoDB installation and connection URI.

❖ Authentication failed

For MongoDB Atlas, verify the database username and password. Also check whether your network address is permitted by the Atlas network access configuration.

❖ Invalid connection string

Ensure that MONGODB_URI starts with a valid MongoDB URI, such as mongodb:// or mongodb+srv://.

❖ Invalid student ID

MongoDB document IDs are not the same as sequential MySQL integer IDs. Use the _id returned by the API.

❖ Missing required fields

Check that the request body contains name, mobile, and course, with non-empty string values.

✦ 10. MongoDB vs MySQL for Node.js

Feature MongoDB MySQL
Database type NoSQL document database Relational database
Main structure Collections and documents Tables and rows
Typical identifier ObjectId Integer or another key type
Schema approach Flexible, optionally enforced through Mongoose Defined table structure
Node.js integration Mongoose or MongoDB driver mysql2 or another SQL client

Neither database is automatically better for every project. Choose based on your data structure, relationships, query needs, team experience, and application requirements.

✦ Best Practices

  • Store database credentials outside your source code.

  • Validate incoming data on the server.

  • Use proper authentication and authorization before exposing student data.

  • Avoid exposing raw internal errors to API clients.

  • Configure suitable database access permissions.

  • Use pagination when returning large collections.

  • Back up important data and test recovery procedures.

  • Add automated tests before deploying the API to production.

✦ Frequently Asked Questions (FAQs)

❖ 1. Can Node.js connect to MongoDB without Mongoose?

Yes. You can use the official MongoDB Node.js driver directly. Mongoose is useful when you want schemas, model methods, and built-in validation features.

❖ 2. Is MongoDB a SQL database?

No. MongoDB is a NoSQL document database. It stores records as documents rather than traditional relational rows.

❖ 3. What is the purpose of Mongoose?

Mongoose helps define document schemas, validate data, create models, and perform database operations from Node.js.

❖ 4. Does MongoDB save data permanently?

MongoDB stores data in its configured database storage. Records normally remain after a Node.js restart, subject to database configuration and storage availability.

❖ 5. Can I build a complete CRUD application with Node.js and MongoDB?

Yes. You can implement create, read, update, and delete operations, then add authentication, authorization, search, pagination, and a frontend dashboard.

✦ Conclusion

Connecting Node.js to MongoDB using Mongoose is a practical way to learn backend development. In this tutorial, you created a project, configured the connection string, defined a student schema and model, and built a working CRUD API.

You can extend this project into a Student Management System, school management application, CRM, inventory platform, or other database-driven application.

To explore programming and technical learning resources, visit Param Classes. For website development and digital solutions, visit ParamWebInfo.

✦ Internal Links

❖ Suggested Blog Tags

Node.js, MongoDB, Mongoose, Node.js MongoDB Tutorial, Express.js, CRUD API, Backend Development, REST API, JavaScript, Database Connectivity

←
Post 24 of 40
→