How to Use Mongoose with NestJS: Simple Guide
To use
mongoose with nestjs, install @nestjs/mongoose and mongoose, then import MongooseModule in your module with your schema. Use @InjectModel in your service to access the model and perform database operations.Syntax
Here is the basic syntax to integrate Mongoose in a NestJS module:
MongooseModule.forRoot('mongodb://localhost/dbname')connects to MongoDB.MongooseModule.forFeature([{ name: 'Cat', schema: CatSchema }])registers a schema.@InjectModel('Cat')injects the model into a service.
typescript
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { Cat, CatSchema } from './schemas/cat.schema'; import { CatsService } from './cats.service'; @Module({ imports: [ MongooseModule.forRoot('mongodb://localhost/nest'), MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }]), ], providers: [CatsService], }) export class AppModule {}
Example
This example shows a simple NestJS app using Mongoose to create and find cats in MongoDB.
typescript
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Cat, CatDocument } from './schemas/cat.schema'; @Injectable() export class CatsService { constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {} async create(name: string, age: number): Promise<Cat> { const newCat = new this.catModel({ name, age }); return newCat.save(); } async findAll(): Promise<Cat[]> { return this.catModel.find().exec(); } } // cat.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; export type CatDocument = Cat & Document; @Schema() export class Cat { @Prop({ required: true }) name: string; @Prop() age: number; } export const CatSchema = SchemaFactory.createForClass(Cat);
Output
When running, you can call CatsService.create('Tom', 3) to add a cat and CatsService.findAll() to get all cats.
Common Pitfalls
Common mistakes include:
- Not calling
MongooseModule.forRoot()to connect to the database. - Forgetting to register schemas with
MongooseModule.forFeature(). - Injecting the model with the wrong name or missing
@InjectModel(). - Not awaiting async database calls.
typescript
/* Wrong: Missing forRoot connection */ @Module({ imports: [ MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }]), ], }) export class AppModule {} /* Right: Include forRoot with connection string */ @Module({ imports: [ MongooseModule.forRoot('mongodb://localhost/nest'), MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }]), ], }) export class AppModule {}
Quick Reference
Summary tips for using Mongoose with NestJS:
- Install
@nestjs/mongooseandmongoosepackages. - Use
MongooseModule.forRoot()once in the root module. - Register schemas with
MongooseModule.forFeature()in feature modules. - Inject models with
@InjectModel()in services. - Use async/await for database operations.
Key Takeaways
Always connect to MongoDB using MongooseModule.forRoot() in your root module.
Register your schemas with MongooseModule.forFeature() to use them in services.
Inject models into services using @InjectModel() for database operations.
Use async/await to handle asynchronous Mongoose calls properly.
Double-check schema names and connection strings to avoid common errors.