NestJs MongoDB 101: Step by Step Connection Guide [2024]



Hello, fellow devs! ❤ When venturing into the world of backend development, we get puzzled about what tools we should choose. Today, I'm going to walk you through one such amazing combination for your backend development💢

NestJS with MongoDB😈

You and I, together will set up our MongoDB and NestJS application. Whether you're an experienced developer or a novice, this coding tutorial guarantees clarity and concrete instructions.

Don't forget to take your favorite beverage😀!

What you should have before jumping into?

  • Basic Typescript
  • NodeJs 
  • MongoDB Connection

Install and Set up the NestJs Application

Using the Nest CLI to set up a new project is really easy. Once npm is installed, use the following instructions in your OS terminal to start a new Nest project:
$ npm i -g @nestjs/cli
$ nest new my-project

This will build a basic Nest.js application and establish "my-project". Some Node.js packages are required for creating this application. 

@nestjs/mongoose
Mongoose

To install these dependencies, change your directory where your project folder is located, for my case, "my-project"

cd my-project

Now, run these command

npm install mongoose @nestjs/mongoose

Configure Mongo Database

MongoDB is used generally to store personnel details. In this case, Mongoose will be used to streamline database interactions. Next, construct the configuration file needed to interact with MongoDB. Go to the src folder and then app.module.ts to set up the configuration:

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [
    MongooseModule.forRoot(process.env.MONGO_CONNECTION_STRING)
  ],
})
export class AppModule {}

Create a User Schema

The database representation of a user is represented by a schema. For creating this database representation, Mongoose schema is used here. Make a schema folder inside the src folder, and then create a user.schema.ts file inside this directory.

$ import {
  Prop,
  Schema,
  SchemaFactory
} from '@nestjs/mongoose';
import {
  Document
} from 'mongoose';

export type UserDocument = User & Document;

@Schema()
export class User {
  @Prop()
  FirstName: string;

  @Prop()
  SurName: string;

  @Prop()
  Email: string;

  @Prop()
  Address: string;

  @Prop()
  Gender: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

Create Client Entity

A typescript class's interface is used to verify types. Each data input must be verified to ensure that it contains the information we intend to add to the database. Inside the src folder, go ahead and create an entities directory. Create a user.entity.ts file within the entities folder, then configure the interface as shown below:

export class User {
  FirstName: string;
  SurName: string;
  Gender: string;
  Email: string;
  Address: string;
}

Define NestJs DTO

Data Transfer Object is what DTO stands for. It specifies how the data will be sent across the network and wraps it. Make a dto directory inside the src folder. Here, a CRUD application is being created. Therefore, to add and modify user data, we must establish DTO.

Make a create-user.dto.ts file and add the following CreateUserDto class to create a user 

import {
  User
} from "../entities/user.entity";

export class CreateUserDto extends User {}

You can create UpdateUserDto class to update a user as well.

Create NestJs Service File

The functionality of a Nest.js API, database interactions, and offering the proper responses are all handled by a service. This service will specify how the database and API interact so that various Mongoose activities can be carried out. 

In the src folder, create the user.service.ts file to set up a service that will carry out these methods:

import {
  Injectable
} from '@nestjs/common';
import {
  InjectModel
} from '@nestjs/mongoose';
import {
  Model
} from 'mongoose';
import {
  CreateUserDto
} from './dto/create-user.dto';
import {
  UpdateUserDto
} from './dto/update-user.dto';
import {
  User,
  UserDocument
} from './schema/user.schema';

@Injectable()
export class UserService {

  constructor(@InjectModel(User.name) private readonly UserModel: Model < UserDocument > ) {}

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

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

  async findOne(id: string) {
    return this.userModel.findById(id);
  }

  async update(id: string, updateUserDto: UpdateUserDto): Promise < UserDocument > {
    return this.userModel.findByIdAndUpdate(id, updateuserDto);
  }

  async remove(id: string) {
    return this.userModel.findByIdAndRemove(id);
  }
}

Add Controller

Controllers allow you to construct routes that execute the service logic you've developed. This allows you to make and process HTTP requests for the API. To handle incoming requests and responses, create a user.controller.ts file in the src directory and add the following controllers using HTTP methods.

import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Put
} from '@nestjs/common';
import {
  UserService
} from './user.service';
import {
  CreateUserDto
} from './dto/create-user.dto'; import { UpdateUserDto
} from './dto/update-user.dto'; @Controller('user') export class UserController { constructor(private readonly userService: UserService) {} @Post() create(@Body() createUserDto: CreateUserDto) { return this.userService.create(createUserDto); } @Get() findAll() { return this.userService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.userService.findOne(id); } @Put(':id') update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) { return this.userService.update(id, updateUserDto); } @Delete(':id') remove(@Param('id') id: string) { return this.userService.remove(id); } }

Create Module

To carry out the above-mentioned logic, we require a module. This will run the controllers and services. To set up a module, create a new file in the src directory named user.module.ts.

import {
  Module
} from '@nestjs/common';
import {
  UserService
} from './user.service';
import {
  UserController
} from './user.controller';
import {
  User,
  UserSchema
} from './schema/user.schema';
import {
  MongooseModule
} from '@nestjs/mongoose';

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

NestJs Project Structure

In a NestJs project, this is the most suitable project structure one should follow:

project-root/
│
├── src/                          # Source code directory
│   ├── app.controller.ts        # Main application controller
│   ├── app.module.ts            # Main application module
│   ├── app.service.ts           # Main application service
│   │
│   ├── modules/                 # Modules directory
│   │   ├── module1/             # Example module 1
│   │   │   ├── controllers/     # Controllers specific to module 1
│   │   │   ├── services/        # Services specific to module 1
│   │   │   ├── module1.module.ts  # Module 1 main module file
│   │   │   └── module1.service.ts # Module 1 main service file
│   │   │
│   │   ├── module2/             # Example module 2
│   │   │   ├── controllers/     # Controllers specific to module 2
│   │   │   ├── services/        # Services specific to module 2
│   │   │   ├── module2.module.ts  # Module 2 main module file
│   │   │   └── module2.service.ts # Module 2 main service file
│   │   │
│   │   └── ...                  # Additional modules
│   │
│   ├── shared/                  # Shared directory for common utilities
│   │   ├── constants.ts         # Constants used across the application
│   │   ├── helpers.ts           # Helper functions
│   │   └── ...                  # Other shared files
│   │
│   └── main.ts                  # Main application entry point
│
├── test/                         # Directory for tests
│   ├── app.e2e-spec.ts          # End-to-end tests
│   └── ...                       # Other test files
│
├── node_modules/                 # Node.js dependencies
├── dist/                         # Compiled JavaScript files (not committed to version control)
├── package.json                  # Project dependencies and scripts
├── tsconfig.json                 # TypeScript configuration
└── README.md                     # Project documentation

Frequently Asked Questions

Is NestJS better than Nodejs?

Both have advantages and disadvantages, and each is better suited to certain uses. At a high level, Node.js provides more flexibility and works well for basic APIs and microservices, but NestJS excels at constructing sophisticated, enterprise-grade systems due to its rich feature set.

What is Mongoose in NestJS?

With Mongoose, everything is based on a Schema. Each schema corresponds to a MongoDB collection and specifies the form of the documents within it.

Is NestJS faster than Laravel?

NestJS outperforms Laravel in terms of performance. NestJS's layout is modular and component-based, influenced by Angular, whereas Laravel's architecture is more typical MVC (Model-View-Controller).

What is DTO in NestJs?

A Data Transfer Object (DTO) is an object that transports data across processes. In NestJs, DTOs are used to describe the structure of data transferred between the client side and the server side. This ensures that the data is properly structured and verified before being processed.

Why use Mongoose instead of MongoDB?

Mongoose validates the schema definitions. The limitations can also apply to documents. Mongoose also offers an abstraction for MongoDB documents.

Can I use Mongoose without MongoDB?

No, Mongoose is a MongoDB-specific Object Data Modeling (ODM) library. It adds an abstraction layer to MongoDB, making database interactions easier. Mongoose cannot be used without MongoDB.

codegirl

Hello, I’m Sangita, person behind "codegirl", a dedicated web developer. Crafting digital experiences is not just my job; it’s my passion. Let’s build something exceptional together!

Post a Comment

Previous Post Next Post