The main objectives of this article are:
(Step 3)
(Step 2):
Next, we have to create a 'username' and 'password' to access our database. Go to the 'Database Access' in the left menu and click on 'Add New Database User'.
- MongoDB
- MongoDB Atlas Cloud Service.
- MongoDB ConnectionString.
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 the binary serialization of JSON. The reading of data from MongoDB is faster when compared to the Relational Database. But MongoDB doesn't have 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 to use MongoDB let's use the MongoDB Atlas Cloud Service.
(Step 1)
Let's go to the MongoDB Atlas website and then signup for 'Free'(Pricing Package).
(Step 2)After registration creates a free cluster and next land on the dashboard page as below.
Now to create a MongoDB collection(table), select 'Database' left side menu and then click on 'Browse Collection'.
(Step 4)
Now click on '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 ConnectionString:
To communicate with MongoDB from our NestJS application, we need the connection string. So let's try to get the connection string.
(Step 1)
First, we have to either register our 'IP Address' or 'Allow Access From Anywhere' at our cloud MongoDB dashboard. Go to 'Network Access' left side menu and click on 'Add IP Address' and then select 'Allow Access From Anywhere'. The 'Allow Access From Anywhere' will permit communication with MongoDB from any IP Address which is good at the time of development.
Next, we have to create a 'username' and 'password' to access our database. Go to the 'Database Access' in the left menu and click on 'Add New Database User'.
(Step 3)
Now to get the connection string go to the 'Database' in the left menu and then click on the 'Connect' button.
(Step 4)
Next, choose the 'Connect your application' option.
Next, choose the 'Connect your application' option.
(Step 5)
Now copy the connection string with some placeholder it looks as below.
mongodb+srv://<username>:<password>@cluster0.igzgk.mongodb.net/<database Name>?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.module.ts:
import { MongooseModule } from '@nestjs/mongoose'; // existng code hidden for the display purpose @Module({ imports: [ MongooseModule.forRoot( 'mongodb+srv://<username>:<password>@cluster0.igzgk.mongodb.net/<database>?retryWrites=true&w=majority', ), ] }) export class AppModule {}
Create A 'Employee' Module In NestJS App:
Let's create a new module like 'Employee' in the NestJS application.
nest g module employee
Create MongoDB Collection Schema In NestJS App:
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 scheme like 'employee-schema.ts'.
nest g class employee/schema/employee-schema --flat --no-spec
src/employee/schema/employee-schema.ts:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; export type EmployeeDocument = Employee & Document; @Schema({ collection: 'Employee' }) export class Employee { @Prop() name: string; @Prop() role: string; @Prop() experience: number; } export const EmployeeSchema = SchemaFactory.createForClass(Employee);
- (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 based on the 'Employee' entity.
src/employee/employee.module.ts:
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { EmployeeSchema } from './schema/employee-schema'; @Module({ imports: [ MongooseModule.forFeature([ { name: 'Employee', schema: EmployeeSchema, collection: 'Employee', }, ]), ], }) export class EmployeeModule {}
Create A Service Like 'EmployeeService' In NestJS App:
Let's create a service file that contains all logic for interacting with the MongoDB
nest g service employee --no-spec
src/employee/employee.service.ts:
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Employee, EmployeeDocument } from './schema/employee-schema'; @Injectable() export class EmployeeService { constructor( @InjectModel(Employee.name) private employeeModel: Model<EmployeeDocument>, ) {} }Here @InjectModel() attribute loads from the '@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 'employeeModl' we can fetch, save, update, 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) | ReactJS(v18) CRUD sample. I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-3 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-4 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-5 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-6 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Part-6 | NestJS(v9) | ReactJS(v18) | MongoDB | CRUD Example
Comments
Post a Comment