How to connect RESTful API & Nest JS backend with MongoDB database?

nadim_ch0wdhury

Nadim Chowdhury

Posted on June 4, 2024

How to connect RESTful API & Nest JS backend with MongoDB database?

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:
   npm install -g @nestjs/cli
Enter fullscreen mode Exit fullscreen mode
  1. Create a New Project:
   nest new project-name
Enter fullscreen mode Exit fullscreen mode
  1. Navigate to the Project Directory:
   cd project-name
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Required Packages

  1. Install Mongoose Package:
   npm install @nestjs/mongoose mongoose
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Mongoose

  1. Create a Mongoose Module Configuration: Open src/app.module.ts and configure the Mongoose module:
   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 {}
Enter fullscreen mode Exit fullscreen mode

Step 4: Define the User Schema and DTO

  1. Create a User Schema: Create the src/user/schemas/user.schema.ts file:
   import { Schema } from 'mongoose';

   export const UserSchema = new Schema({
     name: String,
     email: String,
   });
Enter fullscreen mode Exit fullscreen mode
  1. Create a User DTO: Create the src/user/dto/create-user.dto.ts file:
   export class CreateUserDto {
     readonly name: string;
     readonly email: string;
   }
Enter fullscreen mode Exit fullscreen mode

Step 5: Create the User Service

  1. Implement Service Logic: Open src/user/user.service.ts and implement the service methods:
   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();
     }
   }
Enter fullscreen mode Exit fullscreen mode

Step 6: Create the User Controller

  1. Implement Controller Logic: Open src/user/user.controller.ts and define the routes:
   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);
     }
   }
Enter fullscreen mode Exit fullscreen mode

Step 7: Create the User Interface

  1. Create a User Interface: Create the src/user/interfaces/user.interface.ts file:
   import { Document } from 'mongoose';

   export interface User extends Document {
     readonly name: string;
     readonly email: string;
   }
Enter fullscreen mode Exit fullscreen mode

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:
   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 {}
Enter fullscreen mode Exit fullscreen mode

Step 9: Run the Application

  1. Start the NestJS Application:
   npm run start:dev
Enter fullscreen mode Exit fullscreen mode

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.

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.

💖 💪 🙅 🚩
nadim_ch0wdhury
Nadim Chowdhury

Posted on June 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related