In this section, we will learn how to build a REST API using MongoDB as the database. We will use Node.js and Express.js to create the API endpoints and perform CRUD operations on MongoDB.
Prerequisites
Before we start, make sure you have the following installed:
- Node.js
- npm (Node Package Manager)
- MongoDB
Step 1: Setting Up the Project
-
Create a new directory for your project:
mkdir rest-api-mongodb cd rest-api-mongodb
-
Initialize a new Node.js project:
npm init -y
-
Install the required dependencies:
npm install express mongoose body-parser
Step 2: Setting Up MongoDB Connection
-
Create a new file named
server.js
:const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; // Middleware app.use(bodyParser.json()); // MongoDB connection mongoose.connect('mongodb://localhost:27017/restapi', { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', () => { console.log('Connected to MongoDB'); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
-
Run the server:
node server.js
You should see the message "Connected to MongoDB" and "Server is running on port 3000".
Step 3: Defining the Data Model
- Create a new directory named
models
and a file namedUser.js
inside it:const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: { type: Number, required: true } }); module.exports = mongoose.model('User', userSchema);
Step 4: Creating CRUD Endpoints
-
Create a new directory named
routes
and a file nameduserRoutes.js
inside it:const express = require('express'); const router = express.Router(); const User = require('../models/User'); // Create a new user router.post('/users', async (req, res) => { const user = new User(req.body); try { await user.save(); res.status(201).send(user); } catch (error) { res.status(400).send(error); } }); // Read all users router.get('/users', async (req, res) => { try { const users = await User.find(); res.status(200).send(users); } catch (error) { res.status(500).send(error); } }); // Read a user by ID router.get('/users/:id', async (req, res) => { const _id = req.params.id; try { const user = await User.findById(_id); if (!user) { return res.status(404).send(); } res.status(200).send(user); } catch (error) { res.status(500).send(error); } }); // Update a user by ID router.patch('/users/:id', async (req, res) => { const _id = req.params.id; try { const user = await User.findByIdAndUpdate(_id, req.body, { new: true, runValidators: true }); if (!user) { return res.status(404).send(); } res.status(200).send(user); } catch (error) { res.status(400).send(error); } }); // Delete a user by ID router.delete('/users/:id', async (req, res) => { const _id = req.params.id; try { const user = await User.findByIdAndDelete(_id); if (!user) { return res.status(404).send(); } res.status(200).send(user); } catch (error) { res.status(500).send(error); } }); module.exports = router;
-
Update
server.js
to use the user routes:const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const userRoutes = require('./routes/userRoutes'); const app = express(); const port = 3000; // Middleware app.use(bodyParser.json()); // MongoDB connection mongoose.connect('mongodb://localhost:27017/restapi', { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', () => { console.log('Connected to MongoDB'); }); // Use user routes app.use('/api', userRoutes); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
Step 5: Testing the API
You can use tools like Postman or curl to test the API endpoints.
Create a new user
curl -X POST http://localhost:3000/api/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "[email protected]", "age": 30}'
Read all users
Read a user by ID
Update a user by ID
curl -X PATCH http://localhost:3000/api/users/<user_id> -H "Content-Type: application/json" -d '{"age": 31}'
Delete a user by ID
Conclusion
In this section, we have learned how to build a REST API using MongoDB, Node.js, and Express.js. We covered setting up the project, connecting to MongoDB, defining a data model, creating CRUD endpoints, and testing the API. This knowledge can be extended to build more complex applications and integrate additional features as needed.