How to Build a Simple REST API with Node.js and MongoDB
In this guide, you'll learn how to build a basic REST API using Node.js, Express, and MongoDB. We'll cover project setup, connecting to MongoDB, creating a data model, and implementing CRUD operations step by step.
1. Prerequisites
- Install Node.js (LTS version recommended)
- Have MongoDB Atlas or local MongoDB running
- Basic knowledge of JavaScript
2. Create Your Project Folder
Click to copymkdir rest-api-demo
cd rest-api-demo
npm init -y
3. Install Dependencies
Click to copynpm install express mongoose dotenv
4. Set Up Express Server
Click to copy// index.js
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error(err));
app.get('/', (req, res) => {
res.send('API is running!');
});
app.listen(3000, () => console.log('Server started on port 3000'));
5. Create a Simple Model
Click to copy// models/Note.js
const mongoose = require('mongoose');
const noteSchema = new mongoose.Schema({
title: String,
content: String
});
module.exports = mongoose.model('Note', noteSchema);
6. Implement CRUD Endpoints
Click to copy// index.js (add below existing code)
const Note = require('./models/Note');
// Create
app.post('/notes', async (req, res) => {
const note = new Note(req.body);
await note.save();
res.status(201).json(note);
});
// Read all
app.get('/notes', async (req, res) => {
const notes = await Note.find();
res.json(notes);
});
// Read one
app.get('/notes/:id', async (req, res) => {
const note = await Note.findById(req.params.id);
if (!note) return res.status(404).send('Note not found');
res.json(note);
});
// Update
app.put('/notes/:id', async (req, res) => {
const note = await Note.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!note) return res.status(404).send('Note not found');
res.json(note);
});
// Delete
app.delete('/notes/:id', async (req, res) => {
const note = await Note.findByIdAndDelete(req.params.id);
if (!note) return res.status(404).send('Note not found');
res.json({ message: 'Note deleted' });
});
7. Environment Variables
Click to copy# .env
MONGO_URI=your_mongodb_connection_string
8. Run Your API
Click to copynode index.js
Your API should now be running at http://localhost:3000
. Test your endpoints using Postman or curl.