BlogProgramming

How to Connect NestJs With MongoDB using Mongoonse

Confident businessman watching city sunset through window generated by artificial intelligence

After reading this article, you can connect NestJs With MongoDB using Mongoose.

When I connected my first project of NestJs with MongoDB Using Mongoose, I read a lot of documentation and other resources like YouTube but I never found any that enabled me to connect my NestJS application with MongoDB. But I can say surely after reading this blog you can connect your application with MongoDB. I also have a blog for connecting NodeJs with MongoDB using Mongoose.

Step 1: Install Dependencies

Open your terminal and run the following command to install the necessary packages.

Bash
npm install --save @nestjs/mongoose mongoose

Step 2: Import Required Modules in AppModule

In your app.module.ts file, import the required modules and set up the MongoDB connection.

TypeScript
// app.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/nestjs-mongoose-example'),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Replace the MongoDB connection URL ('mongodb://localhost/nestjs-mongoose-example') with your actual MongoDB URL.

Step 3: Create a Mongoose Schema

Create a Mongoose schema for your data model. For example, let’s create a Cat model in a separate file named cat.model.ts.

TypeScript
// cat.model.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Cat extends Document {
  @Prop()
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

Step 4: Create a Service to Interact with MongoDB

Create a service to handle interactions with MongoDB. For example, create a cats.service.ts file.

TypeScript
// cats.service.ts

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat } from './cat.model';

@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<Cat>) {}

  async create(createCatDto): Promise<Cat> {
    const createdCat = new this.catModel(createCatDto);
    return createdCat.save();
  }

  async findAll(): Promise<Cat[]> {
    return this.catModel.find().exec();
  }
}

Step 5: Use the Service in a Controller

Create a controller to handle HTTP requests. For example, create a cats.controller.ts file.

TypeScript
// cats.controller.ts

import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  async create(@Body() createCatDto) {
    return this.catsService.create(createCatDto);
  }

  @Get()
  async findAll() {
    return this.catsService.findAll();
  }
}

Step 6: Add Controller to AppModule

Update your app.module.ts file to include the newly created controller.

TypeScript
// app.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CatsModule } from './cats/cats.module';

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/nestjs-mongoose-example'),
    CatsModule,
  ],
})
export class AppModule {}

Step 7: Run the Application

Now, you can run your Nest.js application.

Bash
npm run start

Your Nest.js application is connected to MongoDB using Mongoose! You can create and retrieve cats through the /cats endpoint. Customize the code based on your application requirements.

For More Blogs

Leave a Reply

Your email address will not be published. Required fields are marked *