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.
You now understand NestJS Mongoose. Next, formalize the repository pattern over any ORM.