How to use Express JS with Mongoose?
Published: 2024-06-04 05:59:25

Using Express.js with Mongoose is a common setup for building applications with MongoDB. Here's a step-by-step guide to help you get started:

### Step 1: Set Up a New Express.js Project

1. **Initialize a New Project**:
   ```bash
   mkdir express-mongoose-app
   cd express-mongoose-app
   npm init -y
   ```

2. **Install Required Packages**:
   ```bash
   npm install express mongoose
   npm install dotenv
   ```

### Step 2: Configure Environment Variables

1. **Create a `.env` File**:
   Create a `.env` file in the root of your project to store environment variables:
   ```plaintext
   PORT=3000
   MONGODB_URI=mongodb://localhost:27017/mydatabase
   ```

2. **Load Environment Variables**:
   Create a `config.js` file to load environment variables:
   ```javascript
   require('dotenv').config();

   module.exports = {
     port: process.env.PORT || 3000,
     mongodbUri: process.env.MONGODB_URI,
   };
   ```

### Step 3: Set Up Mongoose

1. **Create a Directory Structure**:
   ```bash
   mkdir -p src/models src/controllers src/routes src/config
   ```

2. **Create Mongoose Connection**:
   Create `src/config/mongoose.js` to handle the connection to MongoDB:
   ```javascript
   const mongoose = require('mongoose');
   const config = require('../../config');

   const connectDB = async () => {
     try {
       await mongoose.connect(config.mongodbUri, {
         useNewUrlParser: true,
         useUnifiedTopology: true,
         useCreateIndex: true,
         useFindAndModify: false,
       });
       console.log('MongoDB connected');
     } catch (error) {
       console.error('MongoDB connection failed:', error.message);
       process.exit(1);
     }
   };

   module.exports = connectDB;
   ```

### Step 4: Create Mongoose Models

1. **Create a User Model**:
   Create `src/models/User.js`:
   ```javascript
   const mongoose = require('mongoose');

   const userSchema = new mongoose.Schema({
     name: {
       type: String,
       required: true,
     },
     email: {
       type: String,
       required: true,
       unique: true,
     },
     password: {
       type: String,
       required: true,
     },
   });

   const User = mongoose.model('User', userSchema);

   module.exports = User;
   ```

### Step 5: Create Controllers

1. **Create User Controller**:
   Create `src/controllers/userController.js`:
   ```javascript
   const User = require('../models/User');

   exports.getUsers = async (req, res) => {
     try {
       const users = await User.find();
       res.json(users);
     } catch (error) {
       res.status(500).json({ message: error.message });
     }
   };

   exports.getUser = async (req, res) => {
     try {
       const user = await User.findById(req.params.id);
       if (!user) {
         return res.status(404).json({ message: 'User not found' });
       }
       res.json(user);
     } catch (error) {
       res.status(500).json({ message: error.message });
     }
   };

   exports.createUser = async (req, res) => {
     const { name, email, password } = req.body;

     const userExists = await User.findOne({ email });
     if (userExists) {
       return res.status(400).json({ message: 'User already exists' });
     }

     const user = new User({
       name,
       email,
       password,
     });

     try {
       const newUser = await user.save();
       res.status(201).json(newUser);
     } catch (error) {
       res.status(400).json({ message: error.message });
     }
   };

   exports.updateUser = async (req, res) => {
     try {
       const user = await User.findById(req.params.id);
       if (!user) {
         return res.status(404).json({ message: 'User not found' });
       }

       user.name = req.body.name || user.name;
       user.email = req.body.email || user.email;
       user.password = req.body.password || user.password;

       const updatedUser = await user.save();
       res.json(updatedUser);
     } catch (error) {
       res.status(400).json({ message: error.message });
     }
   };

   exports.deleteUser = async (req, res) => {
     try {
       const user = await User.findById(req.params.id);
       if (!user) {
         return res.status(404).json({ message: 'User not found' });
       }

       await user.remove();
       res.json({ message: 'User deleted' });
     } catch (error) {
       res.status(500).json({ message: error.message });
     }
   };
   ```

### Step 6: Create Routes

1. **Create User Routes**:
   Create `src/routes/userRoutes.js`:
   ```javascript
   const express = require('express');
   const { getUsers, getUser, createUser, updateUser, deleteUser } = require('../controllers/userController');

   const router = express.Router();

   router.get('/users', getUsers);
   router.get('/users/:id', getUser);
   router.post('/users', createUser);
   router.put('/users/:id', updateUser);
   router.delete('/users/:id', deleteUser);

   module.exports = router;
   ```

### Step 7: Set Up the Express Server

1. **Create the Server**:
   Create `src/index.js`:
   ```javascript
   const express = require('express');
   const connectDB = require('./config/mongoose');
   const userRoutes = require('./routes/userRoutes');
   const config = require('../config');

   const app = express();

   // Connect to MongoDB
   connectDB();

   // Middleware to parse JSON
   app.use(express.json());

   // Routes
   app.use('/api', userRoutes);

   const PORT = config.port;
   app.listen(PORT, () => {
     console.log(`Server running on http://localhost:${PORT}`);
   });
   ```

### Step 8: Run the Application

1. **Start the Express Application**:
   ```bash
   node src/index.js
   ```

### Step 9: Test the API

1. **Test 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.
     ```json
     {
       "name": "John Doe",
       "email": "john@example.com",
       "password": "password"
     }
     ```
   - `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 integrating Mongoose with an Express.js application. You can further expand and customize it based on your application's requirements.

Disclaimer: This content is generated by AI.