Mongoose Tutorial
Learn Mongoose step by step: 37 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Mongoose? Learn what Mongoose is, why Node.js developers use it on top of MongoDB, and how schemas, models and documents fit together. Start here.
- Installing Mongoose and Connecting to MongoDB Install Mongoose with npm, write a connection string, connect with mongoose.connect, handle connection events and shut down cleanly.
- Your First Mongoose Model and Document Define your first Mongoose schema, compile a model, create a document, save it to MongoDB and read it back. A complete beginner walkthrough.
- How Mongoose Works: Buffering, Casting and Queries Understand what happens inside Mongoose: command buffering before connect, query objects versus promises, casting, lean results and the document lifecycle.
Schemas and Models
- Mongoose Schema Types Tour every common Mongoose schema type: String, Number, Date, Boolean, ObjectId, Buffer, Mixed, Map, Decimal128, arrays, plus per-type options and casting.
- Mongoose Schema Options, Defaults and Timestamps Configure Mongoose schemas with options: timestamps, strict, collection, versionKey, toJSON, minimize and default values including dynamic defaults.
- Mongoose Virtuals, Getters and Setters Compute fields without storing them: Mongoose virtuals, getters, setters, virtual populate and when to include them in JSON output.
- Mongoose Instance Methods, Statics and Query Helpers Add behavior to your Mongoose models with instance methods, static methods and chainable query helpers, plus plugins for sharing logic across schemas.
- Mongoose Subdocuments, Nested Paths and Arrays Embed data in Mongoose documents with nested paths, single subdocuments and subdocument arrays, and work with array fields, ids and updates.
CRUD and Queries
- Creating Documents in Mongoose Insert data with Mongoose: new Model().save(), Model.create(), insertMany with ordered and unordered options, handling duplicate key and validation errors.
- Finding Documents in Mongoose Read data with Mongoose: find, findOne, findById, countDocuments, exists, projections with select, sorting and what each method returns when nothing matches.
- Mongoose Query Operators and Query Chaining Filter with MongoDB operators in Mongoose ($gt, $in, $or, $regex, $exists) and build queries with the chainable where, sort, limit, skip and populate API.
- Updating Documents in Mongoose Update data in Mongoose with save(), updateOne, updateMany and findOneAndUpdate; use $set, $inc, $push, upserts, returnDocument and runValidators.
- Deleting Documents and Bulk Writes in Mongoose Remove data with Mongoose deleteOne, deleteMany and findOneAndDelete, add soft deletes and TTL expiry, and batch mixed operations with bulkWrite.
- Pagination, Lean Queries and Cursors in Mongoose Paginate Mongoose results with skip and limit, switch to efficient cursor-based (keyset) paging, count totals, and speed up reads with lean and projections.
Validation and Middleware
- Mongoose Validation: Built-in Validators Use Mongoose's built-in validators (required, min, max, minlength, enum, match), understand when validation runs, and read ValidationError details.
- Mongoose Custom Validators and Async Validation Write custom Mongoose validators: sync and async validate functions, cross-field checks, validators on updates, and clean error handling patterns.
- Mongoose Document Middleware: pre and post Hooks Run code before and after saving with Mongoose pre and post hooks: hashing passwords, setting fields, validate hooks, error handling and hook order.
- Mongoose Query and Aggregate Middleware Use Mongoose query middleware for find, update and delete: apply default filters, set updatedAt, handle document versus query hooks and aggregate hooks.
Population and Relations
- References and populate() Learn how Mongoose references work - ObjectId refs, populate(), what it really does behind the scenes, missing documents, and a runnable stand-in that shows the two-query join.
- Populate Options and Nested Populate Control Mongoose populate with select, match, sort, limit and perDocumentLimit, populate several paths, go several levels deep, and see how each option works in a runnable stand-in.
- Virtual Populate for Reverse Relations Learn Mongoose virtual populate - define a reverse relation with localField and foreignField, avoid unbounded arrays of ids, count related documents, and see it in a runnable stand-in.
- Embedding or Referencing Data Decide when to embed subdocuments and when to reference other collections in Mongoose - read patterns, document size, atomicity, duplication, and a runnable comparison of both models.
Aggregation
- The Aggregation Pipeline Basics Learn Model.aggregate() in Mongoose - how pipeline stages transform documents, the core stages $match, $project, $sort, $limit and $count, and a runnable pipeline stand-in.
- Aggregation - $group, $unwind and $lookup Summarize data with $group and accumulators, flatten arrays with $unwind, and join collections with $lookup in Mongoose aggregation - with runnable stand-ins for each stage.
- Facets, Buckets and Aggregation Pagination Build search result pages and dashboards with Mongoose aggregation - $facet for several results at once, $bucket histograms, $dateToString time series and paginated pipelines with total counts.
Indexes and Performance
- Indexes in Mongoose Understand why indexes make queries fast, how to declare them in Mongoose with index, unique and schema.index(), when autoIndex should be off, and a runnable scan-versus-index comparison.
- Compound, Text and TTL Indexes Learn compound index field order and the ESR rule, text indexes with $text search, TTL indexes that expire documents, partial indexes, and runnable stand-ins for each idea.
- Lean Queries, select and Pagination Make Mongoose queries faster - lean() for plain objects, select() projections, skip and limit versus cursor pagination, countDocuments versus estimatedDocumentCount, with runnable stand-ins.
- Bulk Writes, Cursors and Connection Pools Move lots of data efficiently with Mongoose - insertMany, bulkWrite, streaming cursors, batch processing with memory limits and connection pool sizing, with runnable stand-ins.
Testing and Patterns
- Testing Mongoose Code Learn how to test Mongoose applications - unit tests without a database, integration tests with mongodb-memory-server, test isolation, factories and a repository pattern, using node:test.
- Schema Plugins and Reusable Patterns Write Mongoose plugins to share fields, hooks, methods and statics across schemas - soft delete, audit fields and slugs - plus global plugins, options and a runnable plugin stand-in.
- Transactions and Sessions in Mongoose Use multi-document ACID transactions in Mongoose - sessions, withTransaction, passing the session to operations, replica set requirements, retries, and a runnable commit/rollback stand-in.
- Discriminators and Schema Inheritance Model related document types in one collection with Mongoose discriminators - base models, the __t key, extra fields per type, queries across types, embedded discriminators and a runnable stand-in.
Projects and Practice
- Project: A Blog Data Layer Design and build the data layer of a blog with Mongoose - users, posts, comments, slugs, tags, pagination and a tag report - with the real schemas read-only and a runnable in-memory version.
- Project: An Order System with Stock Build an order system with Mongoose - products with stock, orders with price snapshots, atomic stock reservation, idempotent checkout, cancellation and a revenue report - with runnable logic.
- Practice: Mongoose Exercises on Relations and Performance Practice Mongoose populate, aggregation, indexes and bulk operations with eight exercises - each has a runnable stand-in solution, the real Mongoose version and a challenge to extend.