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
Connect MongoDB with Node App using MongooseJS
The process of integrating MongoDB, a NoSQL database, with a Node.js application using MongooseJS, a MongoDB object modelling tool designed to work in an asynchronous environment. Prerequisites:NodejsnpmMongoDBMongooseJSSteps to connect MongoDB with Node AppFollowing are the steps to connect MongoDB
4 min read
How To Set Up Mongoose With Typescript In NextJS ?
Integrating Mongoose with TypeScript in a Next.js application allows you to harness the power of MongoDB while maintaining strong typing and modern JavaScript features. This guide will walk you through the process of setting up Mongoose with TypeScript in a Next.js project, ensuring your application
5 min read
Mongoose Timestamps
Mongoose is a MongoDB object modelling and handling for node.js environment. Mongoose timestamps are supported by the schema. Timestamps save the current time of the document created and also when it was updated in form of a Date by turning it true. When set to true, the mongoose creates two fields
3 min read
Mongoose Schemas Virtuals
Virtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, weâll dive
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
Mongoose Schemas With ES6 Classes
Mongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself. By using loadClass() method: ES6 class methods will become Mongoose methodsES6 class statics will bec
2 min read
npm mongoose
Mongoose is a widely-used Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a powerful framework to interact with MongoDB databases in a more structured and efficient manner. By using Mongoose, developers can easily define schemas, validate data, and perform operations on Mongo
4 min read
Mongoose Schematype.set() API
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose SchemaType setters are SchemaType methods that allow us to transform or manipulate data before it gets stored in MongoDB or before a query is executed. Let's understand more about this with some examples. Creating
2 min read
Mongoose Documents Updating Using save()
An important aspect of a mongoose model is to save the document explicitly when changes have been made to it. This is done using the save() method. In this article, we will see its uses and see the things we should keep in mind while saving our document. We will take the help of an example to unders
6 min read