How to connect RESTful API & Nest JS backend with MongoDB database?
Published: 2024-06-04 05:28:01

Connecting a RESTful API in a NestJS backend with a MongoDB database involves several steps. Here’s a step-by-step guide:

### Step 1: Setup a New NestJS Project
1. **Install Nest CLI**:
   ```bash
   npm install -g @nestjs/cli
   ```
2. **Create a New Project**:
   ```bash
   nest new project-name
   ```
3. **Navigate to the Project Directory**:
   ```bash
   cd project-name
   ```

### Step 2: Install Required Packages
1. **Install Mongoose Package**:
   ```bash
   npm install @nestjs/mongoose mongoose
   ```

### Step 3: Configure Mongoose
1. **Create a Mongoose Module Configuration**:
   Open `src/app.module.ts` and configure the Mongoose module:
   ```typescript
   import { Module } from '@nestjs/common';
   import { MongooseModule } from '@nestjs/mongoose';
   import { UserModule } from './user/user.module';

   @Module({
     imports: [
       MongooseModule.forRoot('mongodb://localhost/nest'),
       UserModule,
     ],
   })
   export class AppModule {}
   ```

### Step 4: Define the User Schema and DTO
1. **Create a User Schema**:
   Create the `src/user/schemas/user.schema.ts` file:
   ```typescript
   import { Schema } from 'mongoose';

   export const UserSchema = new Schema({
     name: String,
     email: String,
   });
   ```

2. **Create a User DTO**:
   Create the `src/user/dto/create-user.dto.ts` file:
   ```typescript
   export class CreateUserDto {
     readonly name: string;
     readonly email: string;
   }
   ```

### Step 5: Create the User Service
1. **Implement Service Logic**:
   Open `src/user/user.service.ts` and implement the service methods:
   ```typescript
   import { Injectable } from '@nestjs/common';
   import { InjectModel } from '@nestjs/mongoose';
   import { Model } from 'mongoose';
   import { User } from './interfaces/user.interface';
   import { CreateUserDto } from './dto/create-user.dto';

   @Injectable()
   export class UserService {
     constructor(@InjectModel('User') private readonly userModel: Model<User>) {}

     async findAll(): Promise<User[]> {
       return this.userModel.find().exec();
     }

     async findOne(id: string): Promise<User> {
       return this.userModel.findById(id).exec();
     }

     async create(createUserDto: CreateUserDto): Promise<User> {
       const createdUser = new this.userModel(createUserDto);
       return createdUser.save();
     }

     async update(id: string, updateUserDto: CreateUserDto): Promise<User> {
       return this.userModel.findByIdAndUpdate(id, updateUserDto, { new: true }).exec();
     }

     async delete(id: string): Promise<User> {
       return this.userModel.findByIdAndRemove(id).exec();
     }
   }
   ```

### Step 6: Create the User Controller
1. **Implement Controller Logic**:
   Open `src/user/user.controller.ts` and define the routes:
   ```typescript
   import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common';
   import { UserService } from './user.service';
   import { CreateUserDto } from './dto/create-user.dto';
   import { User } from './interfaces/user.interface';

   @Controller('users')
   export class UserController {
     constructor(private readonly userService: UserService) {}

     @Get()
     async findAll(): Promise<User[]> {
       return this.userService.findAll();
     }

     @Get(':id')
     async findOne(@Param('id') id: string): Promise<User> {
       return this.userService.findOne(id);
     }

     @Post()
     async create(@Body() createUserDto: CreateUserDto): Promise<User> {
       return this.userService.create(createUserDto);
     }

     @Put(':id')
     async update(@Param('id') id: string, @Body() updateUserDto: CreateUserDto): Promise<User> {
       return this.userService.update(id, updateUserDto);
     }

     @Delete(':id')
     async delete(@Param('id') id: string): Promise<User> {
       return this.userService.delete(id);
     }
   }
   ```

### Step 7: Create the User Interface
1. **Create a User Interface**:
   Create the `src/user/interfaces/user.interface.ts` file:
   ```typescript
   import { Document } from 'mongoose';

   export interface User extends Document {
     readonly name: string;
     readonly email: string;
   }
   ```

### Step 8: Update the User Module
1. **Update the User Module**:
   Open `src/user/user.module.ts` and update it to include the controller, service, and schema:
   ```typescript
   import { Module } from '@nestjs/common';
   import { MongooseModule } from '@nestjs/mongoose';
   import { UserController } from './user.controller';
   import { UserService } from './user.service';
   import { UserSchema } from './schemas/user.schema';

   @Module({
     imports: [MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
     controllers: [UserController],
     providers: [UserService],
   })
   export class UserModule {}
   ```

### Step 9: Run the Application
1. **Start the NestJS Application**:
   ```bash
   npm run start:dev
   ```

### Step 10: Test the RESTful API
1. **Test the API Endpoints**:
   Use a tool like Postman or curl to test the RESTful API endpoints:
   - `GET /users`: Retrieve all users.
   - `GET /users/:id`: Retrieve a user by ID.
   - `POST /users`: Create a new user.
   - `PUT /users/:id`: Update a user by ID.
   - `DELETE /users/:id`: Delete a user by ID.

This guide provides a foundational approach to creating a RESTful API in NestJS 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.