{"success":true,"name":"use-mongoose-lean-for-read-only-mongodb-queries","description":"Fetching Mongoose documents that are only displayed, never modified","category":"ai-brimind","path":"ai-brimind/use-mongoose-lean-for-read-only-mongodb-queries/SKILL.md","file":"SKILL.md","content":"---\nname: use-mongoose-lean-for-read-only-mongodb-queries\ndescription: \"Fetching Mongoose documents that are only displayed, never modified\"\n---\n\n# Use Mongoose lean() for Read-Only MongoDB Queries\n\n## When to use\nProject uses Mongoose on MongoDB, and queries load lists or objects that the code only reads and returns.\n\n## Example request\nLoading 1,000 docs for an API list response → each becomes a full Mongoose document with change tracking; .lean() returns plain objects several times faster. Passing Mongoose docs straight into JSON responses → lean objects serialize predictably, no getter surprises. Calling .save() later on a lean result → lean objects have no save; if you will modify, don't lean — the choice is per-query. Virtuals missing after lean → lean({ virtuals: true }) with the plugin, or compute at the edge; know what lean strips. Each maps to 'hydrated documents cost memory and CPU you only need when writing'.\n\n## Instructions\nAct as a developer who asks 'will this result ever be saved?' before every Mongoose read. For each query: (1) classify it — read-only (rendered, returned by an API, used in a computation) or read-to-modify (fields changed and .save() called), (2) add .lean() to read-only queries so Mongoose skips hydrating full document instances (change tracking, getters/setters, instance methods) and returns plain JavaScript objects — significantly less memory and CPU on large result sets, (3) know exactly what lean removes and check whether the code relies on it: virtuals, defaults applied on read, getters, and document methods all disappear — if a virtual is needed, enable it explicitly or compute it in the mapping layer, (4) never mix: calling save-related logic on a lean object fails, so the classification must be honest, not hopeful. Combine with projection (.select()) for maximum effect: fewer fields, plainer objects. Only mark the query done once its read/write role is confirmed, and explain why the query now pays only for what the code actually does with the data.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1149\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}