api-database-mongoose
Mongoose ODM Patterns
Quick Guide: Use Mongoose as the ODM layer for MongoDB. Document schemas with JSDoc
@typedeffor editor intellisense — no need for TypeScript. Register all middleware before callingmodel(); hooks added after compilation are silently ignored. Use.lean()for any read-only query. Pass{ session }to every operation inside a transaction or enabletransactionAsyncLocalStorage. Prefersession.withTransaction()over manual commit/abort. Use127.0.0.1instead oflocalhostin connection strings (Node.js 18+ IPv6 preference causes timeouts).
CRITICAL: Before Using This Skill
- All code must follow project conventions (kebab-case files, named exports, import ordering, named constants)
- You MUST define all middleware (pre/post hooks) BEFORE calling
model(): hooks registered after model compilation are silently ignored with no error - You MUST pass
{ session }to EVERY operation inside a transaction: missing session causes that operation to run outside the transaction silently - You MUST use
.lean()for read-only queries returning API responses: skipping lean wastes 3x memory on hydration overhead - You MUST use
127.0.0.1instead oflocalhostin connection strings: Node.js 18+ prefers IPv6 andlocalhostcauses connection timeouts - You MUST NOT use
findOneAndUpdate/updateOneand expectpre('save')to fire: onlysave()andcreate()trigger document middleware - You MUST NOT use
next()callbacks in pre hooks on Mongoose 9: use async/await instead;next()was removed in v9
Overview
Auto-detection: Mongoose, mongoose, mongoose.connect, Schema, model, ObjectId, populate, pre('save'), post('save'), lean, mongoose.startSession, withTransaction, discriminator, virtual, Schema.Types.ObjectId, Types.ObjectId