Using Mongoose with NestJS
Last Updated :
14 Jul, 2024
NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It provides a solid foundation for backend development with TypeScript support, built-in decorators, and a modular architecture. Mongoose, on the other hand, is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js. Integrating Mongoose with NestJS allows developers to use the power of MongoDB in a structured and organized manner.
This article will guide you through the process of setting up a NestJS application with Mongoose, creating schemas, and building a basic module, controller, and service to interact with MongoDB.
Prerequisites
Steps to Use Mongoose with NestJS
Step 1: Create a new NestJS project:
nest new nest-gfg
cd nest-gfg
This will create a new directory my-nest-app and set up a basic NestJS project structure inside it.
Step 2: Creating a Basic Module, Controller, and Service
Generate a module:
nest generate module example
Generate a controller:
nest generate controller example
Generate a service:
nest generate service example
Step 3: Install Mongoose using the following command.
npm install @nestjs/mongoose mongoose
Step 4: Install dotenv for security
npm install dotenv
Folder Structure
Folder StructureDependencies
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/mongoose": "^10.0.10",
"@nestjs/platform-express": "^10.0.0",
"dotenv": "^16.4.5",
"mongoose": "^8.5.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}
Example: In this example we will connect to MongoDB Alas and create some data in the collection.
JavaScript
//src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
dotenv.config();
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
JavaScript
//srrc/app.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ExampleModule } from './example/example.module';
@Module({
imports: [
MongooseModule.forRoot('mongodb+srv://Sourav7050:Sclasses%402023@
clustermern.jnu4mto.mongodb.net/?retryWrites=true&w=majority&appName=ClusterMERN'),
ExampleModule,
],
})
export class AppModule { }
JavaScript
//src/example/example.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ExampleController } from './example.controller';
import { ExampleService } from './example.service';
import { Example, ExampleSchema } from './schemas/example.schema';
@Module({
imports: [MongooseModule.forFeature
([{ name: Example.name, schema: ExampleSchema }])],
controllers: [ExampleController],
providers: [ExampleService],
})
export class ExampleModule { }
JavaScript
//src/example/example.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { ExampleService } from './example.service';
@Controller('example')
export class ExampleController {
constructor(private readonly exampleService: ExampleService) { }
@Post()
async create(@Body() createExampleDto: any) {
await this.exampleService.create(createExampleDto);
}
@Get()
async findAll() {
return this.exampleService.findAll();
}
}
JavaScript
//src/example/.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Example, ExampleDocument } from './schemas/example.schema';
@Injectable()
export class ExampleService {
constructor(@InjectModel(Example.name) private exampleModel: Model<ExampleDocument>) { }
async create(createExampleDto: any): Promise<Example> {
const createdExample = new this.exampleModel(createExampleDto);
return createdExample.save();
}
async findAll(): Promise<Example[]> {
return this.exampleModel.find().exec();
}
}
JavaScript
//src/example/schemas/example.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type ExampleDocument = Example & Document;
@Schema()
export class Example {
@Prop({ required: true })
name: string;
@Prop()
age: number;
@Prop()
breed: string;
}
export const ExampleSchema = SchemaFactory.createForClass(Example);
Run the application using the following command.
npm run start
Output
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read