How to Connect RESTful API & Express JS backend with MongoDB database?
Published: 2024-06-04 05:33:32

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
1. **Initialize a New Project**:
   ```bash
   mkdir project-name
   cd project-name
   npm init -y
   ```

2. **Install Required Packages**:
   ```bash
   npm install express mongoose
   npm install typescript ts-node @types/node @types/express
   ```

### Step 2: Configure TypeScript
1. **Create `tsconfig.json`**:
   ```json
   {
     "compilerOptions": {
       "target": "ES6",
       "module": "commonjs",
       "strict": true,
       "esModuleInterop": true,
       "skipLibCheck": true,
       "outDir": "./dist"
     },
     "include": ["src"]
   }
   ```

### Step 3: Set Up Mongoose
1. **Create a Directory Structure**:
   ```bash
   mkdir -p src/models src/controllers src/routes
   ```

### Step 4: Define the User Model
1. **Create User Model**:
   Create `src/models/User.ts`:
   ```typescript
   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
1. **Create User Controller**:
   Create `src/controllers/userController.ts`:
   ```typescript
   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
1. **Create User Routes**:
   Create `src/routes/userRoutes.ts`:
   ```typescript
   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
1. **Create the Server**:
   Create `src/index.ts`:
   ```typescript
   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
1. **Compile and Run the Server**:
   ```bash
   npx ts-node src/index.ts
   ```

### Step 9: Test the RESTful API
1. **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.

Disclaimer: This content is generated by AI.