MongoDB with Mongoose
MongoDB with Mongoose
Not every application fits a relational database. MongoDB is a document database that stores flexible, JSON-like documents — a great fit for content, catalogs, and rapidly-evolving schemas. NestJS integrates it through Mongoose, the most popular MongoDB library for Node.js, via the @nestjs/mongoose package.
SQL vs document thinking
In MongoDB you store documents in collections (rather than rows in tables). Related data is often embedded inside a document instead of split across tables and joined — which can make reads faster but changes how you model data.
Connecting
Defining a schema
With @nestjs/mongoose you define schemas as classes using the @Schema() and @Prop() decorators — familiar after TypeORM entities:
Registering and injecting the model
Register the schema with forFeature(), then inject the model with @InjectModel():
Model provides find, findById, create, updateOne, deleteOne, and more — the document-database equivalent of a repository.
Schema design trade-offs
- Embedding — store related data inside the parent document. Fast reads, but documents can grow large and duplicated data is harder to update.
- Referencing — store an id and look it up separately (like a foreign key). Normalised, but needs an extra query (
populate()).
Summary
MongoDB stores flexible documents in collections, integrated into NestJS via Mongoose and @nestjs/mongoose. Define schemas with @Schema()/@Prop(), register them with forFeature(), and inject a typed Model with @InjectModel() to query and persist. Model embedding vs referencing deliberately. This completes Phase 5 — you can now persist data with relational and document databases. Next: authentication and authorization.