Open In App

Using Mongoose with NestJS

Last Updated : 14 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

rty
Folder Structure

Dependencies

"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



Next Article

Similar Reads