CRUD Operations with Express and MongoDB: A Beginner’s Guide

Learn how to build a simple CRUD application with Express.js and MongoDB. This step-by-step guide covers creating, reading, updating, and deleting data with code examples.


Back to Home

Table of content

Introduction to CRUD with Express and MongoDB

Creating reliable back-end solutions is at the heart of modern web development. Express.js and MongoDB are a popular combination for building fast and scalable applications. In this article, we’ll walk through how to implement CRUD (Create, Read, Update, Delete) operations using Express and MongoDB—essential skills for any web developer.

What Are CRUD Operations?

  • Create – Add new data
  • Read – Retrieve data
  • Update – Modify existing data
  • Delete – Remove data

These four operations form the foundation of most database-driven applications.

Setting Up the Environment

Requirements

  • Node.js & npm installed
  • MongoDB (local or MongoDB Atlas account)
  • Basic knowledge of JavaScript

Project Initialization

mkdir express-mongo-crud
cd express-mongo-crud
npm init -y
npm install express mongoose body-parser

Connecting Express to MongoDB

// app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/crud-demo', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

Defining a Mongoose Model

// models/User.js
const mongoose = require('mongoose');

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

module.exports = mongoose.model('User', userSchema);

Implementing CRUD Routes

Create a New User

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

// CREATE
app.post('/users', async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

Read All Users

// READ
app.get('/users', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

Update a User

// UPDATE
app.put('/users/:id', async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.json(user);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

Delete a User

// DELETE
app.delete('/users/:id', async (req, res) => {
  try {
    await User.findByIdAndDelete(req.params.id);
    res.json({ message: 'User deleted' });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

Testing the API

You can use Postman or curl to test each endpoint. Try creating users and performing read, update, and delete actions to see your CRUD API in action!

Best Practices for CRUD APIs

  • Validate and sanitize user input to prevent security issues.
  • Use environment variables for sensitive configuration.
  • Organize routes and models in separate folders for maintainability.

Conclusion

With Express and MongoDB, building CRUD operations is both powerful and straightforward. Mastering these basics enables you to construct robust APIs, ready to power dynamic web applications. Happy coding!

API
crud
Express.js
mongodb
Node.js
Web Development