Skip to content
Tutorials Center
My learning

Topics

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

  1. 1 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.
  2. 2 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.
  3. 3 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.
  4. 4 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

  1. 5 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.
  2. 6 Mongoose Schema Options, Defaults and Timestamps Configure Mongoose schemas with options: timestamps, strict, collection, versionKey, toJSON, minimize and default values including dynamic defaults.
  3. 7 Mongoose Virtuals, Getters and Setters Compute fields without storing them: Mongoose virtuals, getters, setters, virtual populate and when to include them in JSON output.
  4. 8 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.
  5. 9 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

  1. 10 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.
  2. 11 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.
  3. 12 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.
  4. 13 Updating Documents in Mongoose Update data in Mongoose with save(), updateOne, updateMany and findOneAndUpdate; use $set, $inc, $push, upserts, returnDocument and runValidators.
  5. 14 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.
  6. 15 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

  1. 16 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.
  2. 17 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.
  3. 18 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.
  4. 19 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

  1. 20 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.
  2. 21 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.
  3. 22 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.
  4. 23 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

  1. 24 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.
  2. 25 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.
  3. 26 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

  1. 27 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.
  2. 28 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.
  3. 29 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.
  4. 30 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

  1. 31 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.
  2. 32 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.
  3. 33 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.
  4. 34 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

  1. 35 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.
  2. 36 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.
  3. 37 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.