Technology Blog

Look deep into latest news and innovations happening in the Tech industry with our highly informational blog.

Building modern backend using Nest JS and MongoDB

hkis

Nest JS and MongoDB are superior combination to create large scalable web application backend. Nest JS is progressive framework for building efficient, scalable Node.js web applications, it use express js, fastify and written in typescript. It follows Angular architecture, you can write code using Typescript and it uses decorator pattern similar like how we write API using Spring Boot or Python Flask in same manner Nest JS work. But Nest JS performance is very higher than any other server side rendered framework like Next JS or Nuxt JS due to single threaded asynchronous execution.

In this tutorial we will create a simple backed application for about page using Nest JS and MongoDB and we will Mongoose as ORM for MongoDB.

Installation

Nest JS installation is quite simple similar like Angular.

  1. Install Node JS, it will automatically install Node Package Manager (NPM)
  2. Install Nest JS CLI and create a new project by using this below command
 $ npm i -g @nestjs/cli
 $ nest new demo-app

Create Controller, Module and Services

After creating the project we will create about module, about controller and about service by giving this command

$ nest g module about
$ nest g controller about
$ nest g service about

Install Mongoose

This will create about module, about controller and about service. Next we need to install Nest Mongoose and Mogoose ORM for MongoDB .

$ npm install --save @nestjs/mongoose mongoose
$ npm install --save-dev @types/mongoose

Add Mongoose Module Connect MongoDB Database

So we need to add Mongoose module in app.module.ts (root module) file to connect MongoDB database. So add this line in app.module.ts file to connect MongoDB. So we have created one MongoDB database in heroku and that url we have added MongooseModule.forRoot() paramater to connect MongoDB database.

import { config } from './config';
imports: [MongooseModule.forRoot('mongodb://<username>:<password>1@ds061711.mlab.com:61711/heroku_7q1xt2kd'), AboutModule,]

Add Mongoose Schema

After installing Mongoose we will add schema for about page, for simplicity we will one property in schema and that is text. So create a folder in about folder and give name schemas (about/schemas/about.schema.ts) and then add this line in about.schema.ts file.

import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
export const AboutSchema = new mongoose.Schema({
text: String
});

Add an Interface

So we import mongoose from mongoose and then create AboutSchema. After that we will add interface it defines that how our data object structure will look like. So create a folder name interfaces in about folder like in this way (about/interfaces/about.interface.ts). Now add this line in about.interface.ts file. So interface will inherit property from mongoose Document class and we have add text as string and created_at with current date by using Mongo Date Object and all property are readonly, so we can not change it.

import { Document } from 'mongoose';
export interface About extends Document {
readonly text: string;
readonly created_at: Date;
}

Add a DTO or Object Model

So now we will add an DTO which is important defining object model. It is also useful to define swagger model, so we will add swagger property in here and later we wil add swagger script in main.ts file. Now create a folder name dto in about folder like in this format (about/dto/about.dto.ts) and then add this line in about.dto.ts file. So @ApiProperty() we are using to define the swagger object model definition and it indicates that text field will take string in swagger.

import { ApiProperty } from '@nestjs/swagger';
export class CreateAboutDTO {
@ApiProperty()
readonly text: string;
}

Create Mogoose Service

After defining dto now we can create Mongoose CRUD services in about.service.ts file. So to create simple CRUD operation for MongoDB using Mongoose add those line in about.service.ts file. This are simple mongoose command to do CRUD operation which you can find in mongoose documentation. We are using “id” (MongoDB ID) parameter to update and delete document, this are some of the basic and mandatory CRUD operation that we have written but also you can write more complex queries or aggregation in services.

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { About } from './interfaces/about.interface';
import { CreateAboutDTO } from './dto/about.dto';
@Injectable()
export class AboutService {
constructor(@InjectModel('About') private AboutModel : Model<About>) {}
async create(CreateAboutDTO: CreateAboutDTO): Promise<any> {
const createdCat = new this.AboutModel(CreateAboutDTO);
return createdCat.save();
}
async findAll(): Promise<any> {
return await this.AboutModel.find().exec();
}
async findById(id): Promise<About> {
const customer = await this.AboutModel.findById(id).exec();
return customer;
}
async find(req): Promise<any> {
return await this.AboutModel.find(req).exec();
}
async update(id, CreateAboutDTO: CreateAboutDTO): Promise<any> {
return await this.AboutModel.findByIdAndUpdate(id, CreateAboutDTO, { new: true });
}
async delete(id): Promise<any> {
return await this.AboutModel.findByIdAndRemove(id);
}
}

Create REST API

After adding those line lets create some Rest API for about page, So create some Rest API to Save Data, update Data, Find Data and Delete data. So add this line below line in about.controller.ts file to create REST API.

import { Controller, Res, Query, Get, HttpStatus, Post, Body, Param, NotFoundException, Put, Delete } from '@nestjs/common';
import { AboutService } from './about.service';
import { UsersEmails } from '../config';
import { ApiQuery } from '@nestjs/swagger';
import { CreateAboutDTO } from './dto/about.dto';
@Controller('about')
export class AboutController {
constructor(private readonly AboutService: AboutService) {}
@Post('/create')
async addCustomer(@Res() res, @Body() CreateAboutDTO: CreateAboutDTO) {
const lists = await this.AboutService.create(CreateAboutDTO);
return res.status(HttpStatus.OK).json({
message: "Post has been created successfully",
lists
})
}
@Get('all')
async findAll(@Res() res) {
const lists = await this.AboutService.findAll();
return res.status(HttpStatus.OK).json(lists);
}
@Get('id')
async findById(@Res() res, @Query('id') id: string) {
const lists = await this.AboutService.findById(id);
if (!lists) throw new NotFoundException('Id does not exist!');
return res.status(HttpStatus.OK).json(lists);
}
@Put('/update')
async update(@Res() res, @Query('id') id: string, @Body() CreateAboutDTO: CreateAboutDTO) {
const lists = await this.AboutService.update(id, CreateAboutDTO);
if (!lists) throw new NotFoundException('Id does not exist!');
return res.status(HttpStatus.OK).json({
message: 'Post has been successfully updated',
lists
});
}
@Delete('/delete')
async delete(@Res() res, @Query('id') id: string) {
const lists = await this.AboutService.delete(id);
if (!lists) throw new NotFoundException('Post does not exist');
return res.status(HttpStatus.OK).json({
message: 'Post has been deleted',
lists
})
}
}

Add Collection Name and Schema

So we have created Mongoose Service and Rest API now we need to define a collection name and schema in Feature Module, So in this case it will be About Module. So add this line in import statement to create collection and add Mongoose schema in about.module.ts file.

imports: [MongooseModule.forFeature([{ name: 'About', schema: AboutSchema }])] 

Add Swagger Script in main.ts file

Now we have added four routes namely to do CRUD operation, After adding this line we are all set now we just need to configure the Swaggger API to test it. So we can add swagger by adding this line in main.ts file.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { config } from './config';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder()
.setTitle(config.swaggerApiTitle)
.setDescription(config.swaggerApiDescription)
.setVersion('1.0')
.addTag(config.swaggerApiTitle)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();

Now we have successfully created Nest JS MongoDB Rest api services. You can see test API using directly from Swagger by going to this url

https://localhost:3000/api/

or you can also test it in postman. I think this tutorial will helpful to understand the basic CRUD operation for Nest JS with MongoDB by using Mongooose ORM.

For more information and to develop web application using Node JS, Hire Node Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop web application using Node JS, please visit our technology page.

Content Source:

  1. medium.com