Accessing MongoDB Data via REST API
Introduction
RESTful APIs provide a convenient way to interact with MongoDB databases over HTTP. This tutorial will guide you through the process of creating a REST API to perform CRUD operations on MongoDB data using Node.js and Express.
Setting Up
Before you begin, ensure that you have Node.js and npm installed on your machine. You can install them from the official Node.js website.
Creating a Node.js Application
First, create a new directory for your project and initialize a new Node.js application:
Initializing Node.js Application
mkdir mongodb-rest-api cd mongodb-rest-api npm init -y
Installing Dependencies
Install the necessary dependencies: Express, Mongoose, and body-parser:
Installing Dependencies
npm install express mongoose body-parser
Creating the Server
Create a file named server.js
and set up the Express server:
server.js
const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const app = express(); const port = 3000; app.use(bodyParser.json()); mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }); const User = mongoose.model('User', new mongoose.Schema({ name: String, age: Number })); app.post('/users', async (req, res) => { const user = new User(req.body); await user.save(); res.send(user); }); app.get('/users', async (req, res) => { const users = await User.find(); res.send(users); }); app.get('/users/:id', async (req, res) => { const user = await User.findById(req.params.id); res.send(user); }); app.put('/users/:id', async (req, res) => { const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.send(user); }); app.delete('/users/:id', async (req, res) => { await User.findByIdAndDelete(req.params.id); res.send({ message: 'User deleted' }); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
Running the Server
Start the server using the following command:
Starting the Server
node server.js
Testing the API
You can test the API using a tool like Postman or CURL. Here are some example requests:
Creating a User
POST http://localhost:3000/users Content-Type: application/json { "name": "John Doe", "age": 30 }
Getting All Users
GET http://localhost:3000/users
Conclusion
In this tutorial, you have learned how to create a REST API to perform CRUD operations on MongoDB data using Node.js and Express. This approach allows you to build scalable and efficient APIs for your MongoDB databases.