MongooseModule
Integrates Mongoose, providing models and connection management for MongoDB.
Syntax
MongooseModule.forRoot(uri) | MongooseModule.forFeature([{ name, schema }]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
uri | string | No | The MongoDB connection string. |
Returns
DynamicModule — A module wiring the connection or feature models.
Examples
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Cat, CatSchema } from './cat.schema';
@Module({
imports: [
MongooseModule.forRoot(process.env.MONGO_URL!),
MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }]),
],
})
export class CatsModule {}
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Cat } from './cat.schema';
@Injectable()
export class CatsService {
constructor(@InjectModel(Cat.name) private model: Model<Cat>) {}
create(name: string) {
return this.model.create({ name });
}
}
Notes
Install @nestjs/mongoose and mongoose. Define schemas with the @Schema()
and @Prop() decorators, then register them with forFeature(). Use
forRootAsync() to pull the URI from ConfigService.