Mongoose CRUD Operations

Introduction

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations used to manage data in a database.

When working with MongoDB in Node.js, Mongoose provides methods to create, retrieve, update, and delete documents. Combined with Express.js, these methods help developers build REST APIs for applications such as user management systems, e-commerce websites, and blogs.

In this tutorial, you will learn how to perform Mongoose CRUD operations with practical examples.

What Are CRUD Operations?

Operation Purpose Common Mongoose Method
Create Add new data create()
Read Retrieve data find(), findById()
Update Modify data updateOne(), findByIdAndUpdate()
Delete Remove data deleteOne(), findByIdAndDelete()

Prerequisites

Before starting, you should have Node.js, npm, MongoDB, and basic knowledge of JavaScript and Express.js installed or available.

Set Up the Node.js Project

Create a project and install the required packages:


mkdir mongoose-crud
cd mongoose-crud
npm init -y
npm install express mongoose dotenv

Create the following files:


mongoose-crud/
├── models/
│   └── User.js
├── .env
├── .gitignore
└── app.js

Add your database configuration to .env:


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

Add this to .gitignore:


node_modules/
.env

Keep database credentials out of public repositories.

Create a Mongoose Schema and Model

Create models/User.js:


const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 3,
        trim: true
    },
    email: {
        type: String,
        required: true,
        unique: true,
        lowercase: true,
        trim: true
    },
    age: {
        type: Number,
        min: 18
    },
    isActive: {
        type: Boolean,
        default: true
    }
}, { timestamps: true });
module.exports = mongoose.model('User', userSchema);

The schema defines the document fields and their rules. The User model provides methods to interact with the MongoDB collection. The timestamps option automatically adds createdAt and updatedAt.

Create the Express Server

Create app.js:


const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();

const User = require('./models/User');
const app = express();

app.use(express.json());

async function startServer() {
    try {
        await mongoose.connect(process.env.MONGODB_URI);
        app.listen(process.env.PORT || 3000, () => {
            console.log('Server running');
        });
    } catch (error) {
        console.error('MongoDB connection failed:', error);
    }
}
startServer();

The express.json() middleware allows Express to read JSON request bodies. The server starts after the database connection succeeds.

1. Create Operation

The Create operation adds a new document. Use create():


const user = await User.create({
    name: 'Rahul',
    email: 'rahul@example.com',
    age: 28
});

Mongoose applies schema rules when creating the document. In an Express API, you can create a user using a POST request:


app.post('/api/users', async (req, res) => {
    try {
        const user = await User.create(req.body);
        res.status(201).json(user);
    } catch (error) {
        res.status(400).json({ message: 'Unable to create user' });
    }
});

For production applications, validate incoming request fields and handle duplicate email errors separately.

2. Read Operation

Use find() to retrieve multiple documents:


const users = await User.find();

Find only active users:


const users = await User.find({ isActive: true });

Use findOne() to retrieve one matching document:


const user = await User.findOne({
    email: 'rahul@example.com'
});

Use findById() to find a document by its ID:


const user = await User.findById(userId);

Create a GET API to retrieve all users:


app.get('/api/users', async (req, res) => {
    try {
        const users = await User.find()
            .sort({ createdAt: -1 })
            .limit(10);

        res.json(users);
    } catch (error) {
        res.status(500).json({ message: 'Unable to fetch users' });
    }
});

You can combine filtering, sorting, field selection, and limits to retrieve only the required data.

3. Update Operation

Use updateOne() to update a matching document:


await User.updateOne(
    { email: 'rahul@example.com' },
    { $set: { age: 29 } }
);

To update a document by ID and return the updated version, use findByIdAndUpdate():


const user = await User.findByIdAndUpdate(
    userId,
    { age: 30 },
    { new: true, runValidators: true }
);

Here, new: true returns the updated document, while runValidators: true enables schema validation for supported update operations.

Example PUT API:


app.put('/api/users/:id', async (req, res) => {
    try {
        if (!mongoose.isValidObjectId(req.params.id)) {
            return res.status(400).json({ message: 'Invalid user ID' });
        }

        const user = await User.findByIdAndUpdate(
            req.params.id,
            req.body,
            { new: true, runValidators: true }
        );
        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }
        res.json(user);
    } catch (error) {
        res.status(400).json({ message: 'Unable to update user' });
    }
});

In a production API, also validate which fields clients are allowed to update.

4. Delete Operation

Use deleteOne() to remove one matching document:


await User.deleteOne({ email: 'rahul@example.com' });

To delete a document by ID:


const user = await User.findByIdAndDelete(userId);

Example DELETE API:


app.delete('/api/users/:id', async (req, res) => {
    try {
        if (!mongoose.isValidObjectId(req.params.id)) {
            return res.status(400).json({ message: 'Invalid user ID' });
        }
        const user = await User.findByIdAndDelete(req.params.id);
        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }
        res.json({ message: 'User deleted successfully' });
    } catch (error) {
        res.status(500).json({ message: 'Unable to delete user' });
    }
});

Be careful with deleteMany(), especially when using an empty filter, because it can remove many documents.

Test the CRUD APIs

Use Postman, Insomnia, or another API client to test these endpoints:

Operation HTTP Method Endpoint
Create user POST /api/users
Get users GET /api/users
Get one user GET /api/users/:id
Update user PUT /api/users/:id
Delete user DELETE /api/users/:id

For POST and PUT requests, select JSON as the request body format. Replace :id with an actual MongoDB document ID when testing individual users.

Best Practices for Mongoose CRUD

  • Validate incoming request data and MongoDB ObjectIds.
  • Handle schema validation and duplicate-key errors.
  • Use runValidators: true for supported update operations when appropriate.
  • Return suitable HTTP status codes, such as 201 for creation, 400 for invalid input, and 404 when a document is missing.
  • Use pagination and limits for large collections.
  • Avoid returning sensitive fields in API responses.
  • Keep database credentials in environment variables.
  • Separate models, routes, controllers, and error handling as the application grows.

Remember that unique: true creates or describes a unique index; it is not a normal Mongoose validation rule. Handle duplicate-key errors from MongoDB, commonly identified by error code 11000.

Conclusion

Mongoose simplifies database operations in Node.js by providing methods for creating, reading, updating, and deleting MongoDB documents. When combined with Express.js, these methods make it straightforward to build REST APIs.

Understanding CRUD operations, validating request data, handling errors, and limiting database results will help you develop more reliable applications.

Related Node.js Tutorials