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.
Table of content
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.
These four operations form the foundation of most database-driven applications.
mkdir express-mongo-crud
cd express-mongo-crud
npm init -y
npm install express mongoose body-parser
// 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:'));
// models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number,
});
module.exports = mongoose.model('User', userSchema);
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
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
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
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 });
}
});
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!
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!