Introduction:

Nest CLI Installation:

npm i -g @nestjs/cli

Now create a sample project by using Nest CLI command

nest new your_project_name

package.json:

Now open the package.json file from the sample application created, you can observe few properties like "scripts", "dependencies", and "devDependencies".





"dependencies" contains all plugins to be installed and used them to run the application.





"devDependencies" contain all plugins to be installed and used them at the time of application development.





"scripts" contains a set of commands to build, run and test the application.

Run NestJS Application:

Now to run the application you can find commands in package.json as below

you can observe different modes of the application start commands. Now open a command prompt at package.json physical path and run the command

npm run start

Now application gets run on port 3000, can check by navigating to " http://localhost:3000/".

main.ts:

"main.ts" is an application startup file. Here application startup module(AppModule) gets loaded using NestFactory . An application running port can be defined in the main.ts file. Hereby default application port configured to 3000 port.

app.module.ts:

Modules are used to separate code for easy maintenance and to follow good coding standards. NestJS application can have many modules, but AppModule is the parent of any module in the application.

AppModule gets invoked by the main.ts file on application start.





AppModule holds of "imports(imports modules either application or third-party library modules)", "controllers", and "providers" etc.

Create Controllers:

"@Controller()" decorator on top of the class.

@Controller() is derived from the "@nestjs/common" plugin. @Controller('my_route_value') takes string input value is the route to that controller. Controllers contain a set of action methods, these action methods are responsible for servicing the request to the client by connecting to data sources like database, files, etc.



Now create a new folder name it as "ExtinctAnimals", then inside of folder create the controller and name it as "extinct.animals.controller.ts" and then add a class in that file on top of the class use controller decorator "@Controller('extinctanimals')" with route 'extinctanimals'. Now, this NestJS API end-point can be accessed as "http://localhost:3000/extinctanimals".

MongoDB: Controllers are responsible for accepting the incoming requests and send the response to the client. In NestJS controller is plain class which is decorated with

NestJS supports both Relational and Non-Relational databases. MongoDB is a Non-Relational database, which stores data as documents. Click here to getting started with MongoDB

mongoose and @nestjs/mongoose:

Using Mongoose NestJS plugins, the application can interact with MongoDB. To install the mongoose plugin run the following command

npm install --save @nestjs/mongoose

npm install --save mongoose

Import MongooseModule:

To connect NestJS application with MongoDB, import "MongooseModule" from "@nestjs/mongoose" . MongooseModule.forRoot('your_mongo_connection') need to be imported into the app.module.ts file. Here module is expecting connection as input parameter of MongooseModule.forRoot().

import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [MongooseModule.forRoot("mongodb://localhost:27017/MyWorldDatabase")], controllers: [AppController], providers: [AppService], }) export class AppModule {}





MongoDB connection string "mongodb://localhost:27017" is postfix with database name "MyWorldDatabase".

Mongoose Schema Mapping:

To communicate with MongoDB Collections(Tables) need to map their collection schema with NestJS application Models. Now create folder name as "schema" and add filename as "extinct.animal.schema.ts" and below code into that file.

import * as mongoose from 'mongoose'; export const extinctAnimalSchema = new mongoose.Schema({ Name:String, Location:String, ExtinctYear:Number },{ versionKey:false });

"ExtinctAnimals" is the collection in my MongoDB, schema mapping done by using new mongoose.Schema({})



"versionKey" - by default using NestJS creating a document in MongoDB, it adds extra column "_v" is versioning to the document. To avoid adding this property in document, disable versioning by setting false.





Create Model: Now add a new folder "models", in that add filename as "extinct.animals.model.ts" and add the following code below

export interface ExtinctAnimal{ Name:String, Location:String, ExtinctYear:Number } Update Model Schema To AppModule: Register our schema "extinctAnimalsSchema" into the app module by using MongooseModule.forFeature([]) . By registering schema here, we can access it by injecting them in services where we going to write logic to communicate MongoDB. The "collection" property should match with the MongoDB Collection Name(Here using 'ExtinctAnimals' collection name). Update app.module.ts file as below



import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { MongooseModule } from '@nestjs/mongoose'; import { extinctAnimalSchema } from './Schemas/extinct.animals.schema'; @Module({ imports: [ MongooseModule.forFeature([{ name:'ExtinctAnimals', schema:extinctAnimalSchema, collection:'ExtinctAnimals' }]), MongooseModule.forRoot("mongodb://localhost:27017/MyWorldDatabase") ], controllers: [AppController], providers: [AppService], }) export class AppModule {} Create Service: Now add a new folder name as "Services", then create a new file in that folder and name as "extinct.animal.service.ts".



To make a service file to access by constructor injection, decorate the service class with "@injectable()" decorator provided by "@nestjs/common".



In general "Service" file holds logic to communicate with database calls. Since we are using MongoDB as a database, each service file holds logic to "Collection(Table)" to do that schema that we have created in the above steps need to be injected as Model type(MongoDB Collection Type) through a constructor.



"InjectModel('your_mongoDB_collectionName')" from "@nestj/mongoose" helps to map the schema to MongoDB Collection(Table). The input to string "InjectModel()" should be matched with the one of the name registered in MongooseModule.forFeature([]) in appmodule.





import {Injectable} from '@nestjs/common'; import {Model} from 'mongoose'; import {InjectModel} from '@nestjs/mongoose'; import {ExtinctAnimal} from '../Models/extinct.animals.model' @Injectable() export class ExtinctAnimalService{ constructor(@InjectModel('ExtinctAnimals') private readonly extinctAnimalModel: Model<ExtinctAnimal>){} }

Now "extinctAnimalModel" variable is act as collection in MongoDB.



Now add code in "extinct.animals.service.ts" file, to get all the documents from "ExtinctAnimals" collection in MongoDB

async getAll() { return await this.extinctAnimalModel.find(); } Update AppModule With Service and Controllers: We have to import all our controllers and services to AppModule as below import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { MongooseModule } from '@nestjs/mongoose'; import { ExtinctAnimalsController} from './ExtinctAnimals/extinct.animals.controller'; import { extinctAnimalSchema } from './Schemas/extinct.animals.schema'; import {ExtinctAnimalService} from './Services/extinct.animals.service'; @Module({ imports: [ MongooseModule.forRoot("mongodb://localhost:27017/MyWorldDatabase"),MongooseModule.forFeature([{ name:'ExtinctAnimal', schema:extinctAnimalSchema, collection:'ExtinctAnimals' }]) ], controllers: [AppController,ExtinctAnimalsController], providers: [AppService,ExtinctAnimalService], }) export class AppModule {}

Read Action Method: Create an action method in "extinct.animals.controller.ts" file, to request all the documents from MongoDB. Action method will be decorated with HTTP verbs like '@Get()', '@Post', '@Delete', etc to determine the action method type. These HTTP verbs can contain route value if needed as an input parameter.

import {Controller,Get} from '@nestjs/common'; import {ExtinctAnimalService} from '../Services/extinct.animals.service'; @Controller('extinctanimals') export class ExtinctAnimalsController{ constructor(private service:ExtinctAnimalService){} @Get('all') async GetAll(){ return await this.service.getAll(); } }

ExtinctAnimalService injected into the controller, we have added route value to "@Get('all')" HTTP verb. Now try to navigate to " http://localhost:3000/extinctanimals/all "



Create Action Method: http://localhost:3000/extinctanimals/all

"Mongoose" provided a "save()" method on an injected Model to create a new document in MongoDB.



Create action method that will be decorated with "@Post('add')" Http verb with the route as an input parameter.



Since the post method will return nothing we can assign a "201" status code. In NestJS status codes can be defined as a decorator on top of action method like "@HttpCode(201)"



Data posted to the controller will be received by action method by prefixing "@Body()" to the input object



Update the file "extinct.animals.service.ts" file with below code

async add(animal){ const createAnimal = new this.extinctAnimalModel(animal); await createAnimal.save(); }

Update the file "extinct.animals.controller.ts" with below code

import {Controller,Get,Post,Body} from '@nestjs/common'; @Post('add') async Add(@Body() animal:any){ await this.service.add(animal); }

To test post method use google postman



Update Action Method: "Mongoose" provided methods like "updateOne()" for single update and "updateMany()" for multiple updates on conditionally. This update method takes parameters like conditions and the new objects to be updated.



Update the file "extinct.animals.service.ts" with following code

async update(animal){ await this.extinctAnimalModel.updateOne({ExtinctYear:animal.ExtinctYear},animal); }

Update the file "extinct.animals.controller.ts" with following code

@Post('update') async Update(@Body() animal:any){ await this.service.update(animal); } Delete Action Method: "Mongoose" provided methods like "deleteOne()" for deleting single document and "deleteMany()" for deleting multiple documents.



"@param()" is used to capture the routing value in action methods. Optionally we can pass the name of the routing parameter as input to it like "@param('id')"



"@Delete()" Http verb to represent the action method type



Update the file "extinct.animals.service.ts" with the following code

async delete(id){ await this.extinctAnimalModel.deleteOne({_id :id}); }

Update the file "extinct.animals.controller.ts" with the following code

import {Controller,Get,Post,Body, Delete,Param} from '@nestjs/common'; import {ExtinctAnimalService} from '../Services/extinct.animals.service';

@Delete('delete/:id') async Delete(@Param('id') id){ await this.service.delete(id); }

Refer: MongoDB Quick Start NestJS Sample Source Code

Update the file "extinct.animals.controller.ts" with below codeTo test post method use google postman"Mongoose" provided methods like "updateOne()" for single update and "updateMany()" for multiple updates on conditionally. This update method takes parameters like conditions and the new objects to be updated.Update the file "extinct.animals.service.ts" with following codeUpdate the file "extinct.animals.controller.ts" with following code"Mongoose" provided methods like "deleteOne()" for deleting single document and "deleteMany()" for deleting multiple documents."@param()" is used to capture the routing value in action methods. Optionally we can pass the name of the routing parameter as input to it like "@param('id')""@Delete()" Http verb to represent the action method typeUpdate the file "extinct.animals.service.ts" with the following codeUpdate the file "extinct.animals.controller.ts" with the following code

NestJS is a framework used to develop server-side applications. NestJS built on top of Node.js frameworks like Express. It is a combination of Progressive Javascript, Object-Oriented Programming, Functional Programming, and Functional Reactive Programming.Using Nest CLI we are able to generate the NestJS starter project with the default template. To install Nest CLI globally over our system open command prompt and run the command