How to Build a REST API with Express.js and MongoDB in 10 Minutes


Introduction
In this guide, we'll quickly build a simple REST API using Express.js and MongoDB. Whether you're new to backend development or need a refresher, this tutorial will help you start with a basic CRUD (Create, Read, Update, Delete) API.
What You'll Learn:
Setting up an Express.js server
Connecting to MongoDB
Creating API routes
Performing CRUD operations
Testing the API using Postman
Prerequisites:
Node.js installed
Basic understanding of JavaScript
MongoDB Atlas account (or local MongoDB setup)
Step 1: Setting Up the Project
Open your terminal and create a new project:
mkdir express-mongo-api && cd express-mongo-api
npm init -y
Install required dependencies:
npm install express mongoose dotenv cors body-parser
express – Web framework for Node.js
mongoose – ODM for MongoDB
dotenv – Manage environment variables
cors – Handle cross-origin requests
body-parser – Parse incoming JSON data
Step 2: Connecting to MongoDB
Create a .env
file in the root directory and add your MongoDB connection string:
MONGO_URI=your_mongodb_connection_string
PORT=5000
Now, create a file db.js
to establish the database connection:
const mongoose = require('mongoose');
require('dotenv').config();
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB Connected'))
.catch(err => console.error(err));
module.exports = mongoose;
Step 3: Defining the User Model
Inside a models
folder, create User.js
:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
module.exports = mongoose.model('User', userSchema);
Step 4: Building API Routes
Create a routes
folder and add userRoutes.js
:
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// Create a user
router.post('/', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Get all users
router.get('/', async (req, res) => {
const users = await User.find();
res.json(users);
});
// Get a user by ID
router.get('/:id', async (req, res) => {
const user = await User.findById(req.params.id);
res.json(user);
});
// Update a user
router.put('/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(user);
});
// Delete a user
router.delete('/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.json({ message: 'User deleted' });
});
module.exports = router;
Step 5: Setting Up the Express Server
Create server.js
in the root directory:
const express = require('express');
require('dotenv').config();
require('./db'); // Connect to MongoDB
const app = express();
app.use(express.json()); // Middleware to parse JSON
app.use('/users', require('./routes/userRoutes')); // Use user routes
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Run the server:
node server.js
You should see "MongoDB Connected" and "Server running on port 5000" in your terminal.
Step 6: Testing the API with Postman
Use Postman or cURL to test the API:
Create a user (POST /users
)
{
"name": "John Doe",
"email": "johndoe@example.com",
"age": 25
}
Get all users (GET /users
)
Returns an array of users.
Get a user by ID (GET /users/:id
)
Fetches a specific user by their ID.
Update a user (PUT /users/:id
)
Send an updated JSON object.
Delete a user (DELETE /users/:id
)
Removes a user from the database.
Optional: Deploying the API
Deploy to Render, Vercel, or Railway for free hosting.
Use MongoDB Atlas instead of local MongoDB.
Add authentication using JWT (JSON Web Tokens).
Subscribe to my newsletter
Read articles from Ayush Kumar Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ayush Kumar Singh
Ayush Kumar Singh
I am a college student pursuing majors in Computer Applications with a keen interest in data science and machine leaning.