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
Using TypeORM with NestJS NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. One of the powerful features of NestJS is its ability to easily integrate with databases using TypeORM, a popular ORM (Object-Relational Mapping) tool. This article will guide you through the proc
3 min read
How To Set Up Mongoose With Typescript In NextJS ? Combining Mongoose with TypeScript in a Next.js project is an intelligent approach to develop scalable, type-safe, and maintainable full-stack web applications. Mongoose offers a powerful ODM (Object Data Modeling) layer to interact with MongoDB, and TypeScript provides static typing to detect issue
5 min read
How To Set Up Mongoose With Typescript In NextJS ? Combining Mongoose with TypeScript in a Next.js project is an intelligent approach to develop scalable, type-safe, and maintainable full-stack web applications. Mongoose offers a powerful ODM (Object Data Modeling) layer to interact with MongoDB, and TypeScript provides static typing to detect issue
5 min read
How to Use MongoDB and Mongoose with Node.js ? MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
6 min read
Mongoose Tutorial Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam
6 min read
What is NestJS? NestJS is a powerful framework for building efficient and scalable server-side applications. Developed with a focus on modern JavaScript and TypeScript, NestJS combines object-oriented programming, functional programming, and reactive programming. In this article, we will learn in-depth about NestJS
3 min read