The main objectives of this article are:
(Step 3)
(Step 4)
(Step: 2)
(Step:4)
- MongoDB
- MongoDB Atlas Cloud Service
- MongoDB ConnectionString
- Install Mongo Libraries In NestJS App
- Create A 'SuperHeroes' Module In NestJS App
- Create A Service Like 'SuperHeroesService' In NestJS App
MongoDB:
MongoDB is a document-oriented database, which is classified as a NoSQL database. In MongoDB, tables are called collections, and records are called documents. It stores data in BSON format. The BSON is binary serialization of JSON. The reading of data from MongoDB is faster when compared to the Relational Database. But MongoDB doesn't have a relation between the collections. We can't declare NoSQL is better than SQL or vice-versa. So depending on the application requirement either select NoSQL or SQL or Both databases.
MongoDB Atlas Cloud Service:
For our demo of using MongoDB let's use the MongoDB Atlas cloud service.
(Step 1)So let's go to the MongoDB Atlas website and then signup for 'Free'(pricing package).
(Step 2)After successful registration and then create a cluster and next land on the dashboard as below.
Now to create a MongoDB collection(table), select 'Database' left side menu and click on the 'Browser Collection'.
Now select 'Add My Own Data' for creating the new database and new collection.
(Step: 5)
Click on 'Insert Document' to add a new document to the database.
MongoDB Connection:
To communicate with MongoDB from our NestJS application, we need the connection string. So let's try to get the connection.
(Step: 1) First we have to register our 'IP address' at our cloud MongoDB dashboard. Go to 'Network Access' left-hand side menu and then click on 'Add IP Address' and then add our public IP address.
Next, we have to create a 'username' and 'password' to access our database. Go to the 'Database Access' menu on left-hand side and then click on 'Add New Database User'.
(Step: 3)
Now to get the connection string go to the 'Database' left-hand side menu and then click on the 'Connect' button
Next, choose the 'Connect your application' option
(Step 5)Now copy the connection string with some place holder it looks as below
mongodb+srv://<username>:<password>@cluster0.igzgk.mongodb.net/<databasename>?retryWrites=true&w=majority
- Here we have placeholders like 'username', 'password', and 'database'. If you don't specify the database name at the end and just before the query params then it tries to search for the default database like 'Test'.
Install Mongo Libraries In NestJS App:
In the NestJS application to communicate with MongoDB, we are going to depend on libraries like 'mongoose', '@nestjs/mongoose'
npm i @nestjs/mongoose mongoose
Configure MongoDB ConnectionString In NestJS App:
In the 'AppModule' configure the MongoDB connection string by importing the 'MongooseModule'.
src/app/app.module.ts:
import { MongooseModule } from '@nestjs/mongoose';
// existing code hidden for display purpose
@Module({
imports: [
MongooseModule.forRoot(
'mongodb+srv://<username>:<password>@cluster0.igzgk.mongodb.net/<databasename>?retryWrites=true&w=majority',
),
],
})
export class AppModule {}
Create A 'SuperHeroes' Module In NestJS App:
Let's create a new module like 'SuperHeroes' in the NestJS application
nest g mo super-heroes
Create MongoDB Collection Schema In NestJS Application:
To communicate with the MongoDB collection(table) from the nestjs application we have to define the schema. The schema is the entity representation of the MongoDB collection.
So let's create a schema like 'super-heroes-schema.ts'.
nest g cl super-heroes/schema/super-heroes.schema --flat --no-spec
src/app/super-heroes/schema/super-heroes.schema.ts:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; export type SuperHeroesDocument = SuperHeroes & Document @Schema({collection:'SuperHeroes'}) export class SuperHeroes { @Prop() name:string; @Prop() franchise:string; @Prop() powers:string; @Prop() imageUrl:string; } export const SuperHeroesSchema = SchemaFactory.createForClass(SuperHeroes);
- (Line: 6) Here we can explicitly map the entity with MongoDB collection by specifying the collection name inside of the 'Schema' attribute.
- (Line: 8-18) Here class properties are mapped with the MongoDB document property with help of the '@Prop()' attribute.
- (Line: 21) Creating the MongoDB schema base on the 'SuperHeroes' entity.
src/app/super-heroes/super-heroes.module.ts:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { SuperHeroesSchema } from './schema/super-heroes.schema';
@Module({
imports: [
MongooseModule.forFeature([
{
name: 'SuperHeroes',
schema: SuperHeroesSchema,
collection: 'SuperHeroes',
},
]),
],
})
export class SuperHeroesModule {}
Create A Service Like 'SuperHeroesService' In NestJS App:
Let's create a service file that contains all logic for interacting with the MongoDB
nest g s super-heroes --no-spec
src/app/super-heroes/super-heroes.service.ts:
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { SuperHeroes, SuperHeroesDocument } from './schema/super-heroes.schema'; @Injectable() export class SuperHeroesService { constructor( @InjectModel(SuperHeroes.name) private superHeroModel: Model<SuperHeroesDocument>, ) {} }
- Here @InjectModel() attribute loads from '@nestjs/mongoose' here we need to pass our collection entity name and model type define using the 'Model' that loads from the 'mongoose' library. Now using the 'superHeroModel' we can fetch, save, update, and delete from the MongoDB.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on NestJS (v9) and Angular(v4). using I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-2 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-5 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-6| NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-5 | NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Part-6| NestJS(v9) | Angular(v14) | MongoDB | CRUD Example
Comments
Post a Comment