How to connect RESTful API & Nest JS backend with MongoDB database?
Nadim Chowdhury
Posted on June 4, 2024
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
- Install Nest CLI:
npm install -g @nestjs/cli
- Create a New Project:
nest new project-name
- Navigate to the Project Directory:
cd project-name
Step 2: Install Required Packages
- Install Mongoose Package:
npm install @nestjs/mongoose mongoose
Step 3: Configure Mongoose
-
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 {}
Step 4: Define the User Schema and DTO
-
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,
});
-
Create a User DTO:
Create the
src/user/dto/create-user.dto.ts
file:
export class CreateUserDto {
readonly name: string;
readonly email: string;
}
Step 5: Create the User Service
-
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();
}
}
Step 6: Create the User Controller
-
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);
}
}
Step 7: Create the User Interface
-
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;
}
Step 8: Update the User Module
-
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 {}
Step 9: Run the Application
- Start the NestJS Application:
npm run start:dev
Step 10: Test the RESTful API
-
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 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
privacy Caught in the Crunch My Journey from Snacks to 2 Million Exposed Users Privacy
November 30, 2024
devchallenge Submission for the DevCycle Feature Flag Challenge: Feature Flag Funhouse
November 30, 2024