Building RESTful APIs with Node.js and MongoDB
1. Setup Node.js and Express.js
Install Node.js from the official website if you haven't already. Create a new directory for your project and navigate into it using the terminal. Initialize a new Node.js project using npm:
npm init -y
Install Express.js and other necessary packages:
npm install express mongoose body-parser
2. Create the Server
Create a new file, e.g., server.js
, and require Express and other dependencies:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
// Middleware for parsing JSON requests
app.use(bodyParser.json());
3. Connect to MongoDB
Set up a connection to your MongoDB database using Mongoose:
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
4. Define Mongoose Schema and Model
Create a new folder, e.g., models
, and define a Mongoose schema for your data model, e.g., Task.js
:
const mongoose = require('mongoose');
const taskSchema = new mongoose.Schema({
title: { type: String, required: true },
description: { type: String, required: true },
completed: { type: Boolean, default: false },
});
const Task = mongoose.model('Task', taskSchema);
module.exports = Task;
5. Create API Routes
Create a new folder, e.g., routes
, and define API routes using Express, e.g., tasks.js
:
const express = require('express');
const Task = require('../models/Task');
const router = express.Router();
// GET all tasks
router.get('/', async (req, res) => {
try {
const tasks = await Task.find();
res.json(tasks);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// POST a new task
router.post('/', async (req, res) => {
const task = new Task({
title: req.body.title,
description: req.body.description,
});
try {
const newTask = await task.save();
res.status(201).json(newTask);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
module.exports = router;
6. Use API Routes in the Main App
In server.js
, import and use the API routes:
const tasksRouter = require('./routes/tasks');
app.use('/api/tasks', tasksRouter);
7. Start the Server
Add the code to start the Express server:
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
8. Run the Application
Start your Node.js server using:
node server.js
9. Test the APIs
Use tools like Postman or cURL to send HTTP requests to your API endpoints (e.g., GET /api/tasks
, POST /api/tasks
).
10. Handle Additional CRUD Operations
Expand your API routes to handle update (PUT), delete (DELETE), and other CRUD operations as needed. Implement validation, error handling, authentication, and authorization based on your application requirements.
11. Continuous Learning
Learning MongoDB is an ongoing process. Keep exploring new features, experimenting with different use cases, and improving your skills through practice and hands-on experience.
No comments:
Post a Comment