Skip to content

NestJS Mongoose

Mongoose is Nest's primary MongoDB integration. This lesson covers MongooseModule, schema classes, and model injection into services.

Connecting Mongoose in Nest

@nestjs/mongoose provides MongooseModule.forRoot() for the connection and forFeature() for registering schemas that become injectable models.

MongooseModule.forRoot(process.env.MONGODB_URI);

@Schema()
export class Cat {
  @Prop({ required: true })
  name: string;

  @Prop()
  age: number;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

@Schema() / @Prop() keep Nest-style decorator syntax while generating a Mongoose schema via SchemaFactory.

Injecting a Model

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

  create(dto: CreateCatDto) {
    return this.catModel.create(dto);
  }
}
  • Register the schema with MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }]).
  • @InjectModel(Cat.name) injects the compiled Mongoose model.
  • Documents return lean objects when you call .lean() for better performance on reads.
  • Use indexes and unique constraints in schema props for fields queried often.

Mongoose Nest Cheatsheet

Key decorators and APIs for Nest + MongoDB.

API Purpose
MongooseModule.forRoot(uri) Connect to MongoDB
@Schema() / @Prop() Define a document schema
SchemaFactory.createForClass() Build a Mongoose schema from a class
@InjectModel(name) Inject a model into a provider
model.find() / create() Query and write documents

Embedded Documents and References

MongoDB favors embedding related data when it is owned by a parent document. Use ObjectId references and populate() when data is shared across collections.

Validation Layers

Still validate HTTP input with Nest DTOs and ValidationPipe. Schema-level Mongoose validation is a second line of defense, not a replacement for API validation.

Common Mistakes

  • Treating Mongoose documents as plain objects without converting when needed (toJSON / lean).
  • Forgetting unique indexes and then handling duplicates only as generic 500 errors.
  • Over-using populate() on large lists without pagination.
  • Hard-coding MongoDB URIs instead of ConfigModule environment variables.

Key Takeaways

  • @nestjs/mongoose registers connections and feature schemas as Nest providers.
  • Class-based schemas with @Schema/@Prop keep models consistent with Nest style.
  • Inject models with @InjectModel and keep queries in services.
  • Combine Nest DTO validation with schema constraints for safer writes.

Pro Tip

Enable timestamps: true on schemas that need createdAt/updatedAt instead of managing those fields manually in every service method.