When to Use Mongoose’s .lean(): Boost Read Performance by Skipping Hydration
Use Mongoose’s .lean() to skip document hydration on read‑heavy endpoints, saving CPU and memory. Learn when it’s safe, how to enable virtuals, and benchmark the benefit.
ReadMeFeed / Community knowledge
Real questions. Useful conversations. Find the people who know your stack.
Use Mongoose’s .lean() to skip document hydration on read‑heavy endpoints, saving CPU and memory. Learn when it’s safe, how to enable virtuals, and benchmark the benefit.
Mongoose middleware lets you run code automatically on document lifecycle events. This guide shows how to use pre‑save hooks for data normalization, post‑save hooks for side effects, and query middleware for updates. It also covers common pitfalls and when to avoid middleware.
Use Mongoose ClientSession to scope multiple model writes to one MongoDB transaction, with session lifecycle and failure handling.
Use Mongoose sessions only when writes must span documents atomically. This note covers the minimal session pattern, trust boundaries, replica set prerequisites, and how to monitor transaction health.
Centralize data normalization, validation, and audit logging inside your Mongoose schemas using pre and post middleware instead of duplicating logic across application code.
Mongoose hydrates every query result into a Document by default. Append `.lean()` to return plain JavaScript objects for serialization-only endpoints, and learn where that shortcut breaks.
Learn how to hash passwords automatically before they are saved, avoid re‑hashing on updates, and understand where the hook does not run.
Add automatic createdAt and updatedAt fields to Mongoose schemas using default values and pre‑save middleware, with steps to verify and recover.
Learn how to define virtual getters and setters in Mongoose so computed values like full names appear in API responses without extra storage or index overhead.