Connecting a RESTful API in an Express.js backend with a MongoDB database involves several steps. Here’s a step-by-step guide:
Step 1: Set Up a New Express.js Project
- Initialize a New Project:
mkdir project-name
cd project-name
npm init -y
- Install Required Packages:
npm install express mongoose
npm install typescript ts-node @types/node @types/express
Step 2: Configure TypeScript
-
Create
tsconfig.json
:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist"
},
"include": ["src"]
}
Step 3: Set Up Mongoose
- Create a Directory Structure:
mkdir -p src/models src/controllers src/routes
Step 4: Define the User Model
-
Create User Model:
Create
src/models/User.ts
:
import { Schema, model } from 'mongoose';
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true }
});
export const User = model('User', userSchema);
Step 5: Create the User Controller
-
Create User Controller:
Create
src/controllers/userController.ts
:
import { Request, Response } from 'express';
import { User } from '../models/User';
export const getUsers = async (req: Request, res: Response) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).send(err);
}
};
export const getUser = async (req: Request, res: Response) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).send('User not found');
}
res.json(user);
} catch (err) {
res.status(500).send(err);
}
};
export const createUser = async (req: Request, res: Response) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (err) {
res.status(400).send(err);
}
};
export const updateUser = async (req: Request, res: Response) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
if (!user) {
return res.status(404).send('User not found');
}
res.json(user);
} catch (err) {
res.status(400).send(err);
}
};
export const deleteUser = async (req: Request, res: Response) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).send('User not found');
}
res.send('User deleted');
} catch (err) {
res.status(500).send(err);
}
};
Step 6: Create the User Routes
-
Create User Routes:
Create
src/routes/userRoutes.ts
:
import { Router } from 'express';
import { getUsers, getUser, createUser, updateUser, deleteUser } from '../controllers/userController';
const router = Router();
router.get('/users', getUsers);
router.get('/users/:id', getUser);
router.post('/users', createUser);
router.put('/users/:id', updateUser);
router.delete('/users/:id', deleteUser);
export default router;
Step 7: Set Up the Express Server
-
Create the Server:
Create
src/index.ts
:
import express from 'express';
import mongoose from 'mongoose';
import userRoutes from './routes/userRoutes';
const app = express();
mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('Error connecting to MongoDB', err);
});
app.use(express.json());
app.use('/api', userRoutes);
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Step 8: Compile TypeScript and Run the Server
- Compile and Run the Server:
npx ts-node src/index.ts
Step 9: Test the RESTful API
-
Test the API Endpoints:
Use a tool like Postman or curl to test the RESTful API endpoints:
-
GET /api/users
: Retrieve all users. -
GET /api/users/:id
: Retrieve a user by ID. -
POST /api/users
: Create a new user. -
PUT /api/users/:id
: Update a user by ID. -
DELETE /api/users/:id
: Delete a user by ID.
-
This guide provides a foundational approach to creating a RESTful API in an Express.js backend connected to a MongoDB database. You can further expand and customize it based on your application's requirements.
If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!
Disclaimer: This content is generated by AI.