Building a RESTful API with Node.js, Express, and MongoDB: A Step-by-Step Guide
In this tutorial, we’ll walk through how to set up a RESTful API using Node.js, Express, and MongoDB. We’ll cover creating routes to perform CRUD operations (Create, Read, Update, Delete) on MongoDB documents. By the end, you’ll have a functioning API that can handle basic database interactions.
Prerequisites
- Node.js installed on your machine
- Basic understanding of JavaScript and Node.js
- MongoDB installed locally or a MongoDB Atlas account (for cloud hosting)
Step 1: Set Up Your Project
Start by setting up a new Node.js project. Open your terminal and run the following commands:
mkdir node-express-mongodb-api
cd node-express-mongodb-api
npm init -y
Next, install the required dependencies:
npm install express mongoose body-parser
- Express: For building the RESTful API framework
- Mongoose: MongoDB object modeling tool for Node.js
- body-parser: Middleware to parse incoming request bodies
Step 2: Create an Express Server
Create a new file named index.js
in the project root directory.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
// MongoDB Connection
mongoose.connect('mongodb://localhost/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
// Routes
app.get('/', (req, res) => {
res.send('Welcome to the API');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 3: Define MongoDB Schema and Model
Create a new folder named models
and inside it, create a file item.js
.
const mongoose = require('mongoose');
const itemSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String }
});
const Item = mongoose.model('Item', itemSchema);
module.exports = Item;
Step 4: Create CRUD Routes
Create a new folder named routes
and inside it, create a file items.js
.
const express = require('express');
const router = express.Router();
const Item = require('../models/item');
// Create a new item
router.post('/', async (req, res) => {
try {
const newItem = await Item.create(req.body);
res.status(201).json(newItem);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Get all items
router.get('/', async (req, res) => {
try {
const items = await Item.find();
res.json(items);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// Update an item
router.patch('/:id', async (req, res) => {
try {
const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updatedItem);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Delete an item
router.delete('/:id', async (req, res) => {
try {
await Item.findByIdAndDelete(req.params.id);
res.json({ message: 'Item deleted' });
} catch (err) {
res.status(400).json({ message: err.message });
}
});
module.exports = router;
Step 5: Integrate Routes with Express Server
Update index.js
to use the items
routes.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
// MongoDB Connection
mongoose.connect('mongodb://localhost/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
// Routes
const itemsRouter = require('./routes/items');
app.use('/items', itemsRouter);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 6: Test Your API
Start your Node.js server by running node index.js
in the terminal. Use tools like Postman or curl
to interact with your API endpoints:
POST /items
: Create a new itemGET /items
: Get all itemsPATCH /items/:id
: Update an itemDELETE /items/:id
: Delete an item
Conclusion
You’ve successfully set up a RESTful API using Node.js, Express, and MongoDB! This example covers basic CRUD operations. You can expand this project by adding authentication, error handling, input validation, and more complex querying.