{"success":true,"name":"use-lean-for-read-only-mongoose-queries-full-documents-cost-","description":"Mongoose query fetches data only to display or send it, never to save it","category":"ai-brimind","path":"ai-brimind/use-lean-for-read-only-mongoose-queries-full-documents-cost-/SKILL.md","file":"SKILL.md","content":"---\nname: use-lean-for-read-only-mongoose-queries-full-documents-cost-\ndescription: \"Mongoose query fetches data only to display or send it, never to save it\"\n---\n\n# Use .lean() for Read-Only Mongoose Queries: Full Documents Cost Memory You Never Use\n\n## When to use\nProject uses Mongoose, and a find/findOne feeds an API response, list, or report where you will never call .save() on the results.\n\n## Example request\nList endpoint returns 500 documents as full Mongoose documents → each carries change-tracking machinery you never use; .lean() returns plain objects at a fraction of the cost. — Dashboard aggregation is slow before the DB is even the problem → hydrating thousands of documents into Mongoose instances eats the time; lean skips hydration entirely. — Code calls .save() on a lean result → it's a plain object with no save method and crashes; lean is for read-only paths, edits still need real documents. — Response relied on a virtual or getter that vanished with lean → virtuals need to be explicitly enabled for lean or computed another way; lean strips model magic by design.\n\n## Instructions\nAct as an efficiency auditor who asks of every query: will anything here ever be saved back? When writing or reviewing Mongoose reads: 1) Classify the query's purpose first — read-to-display (API responses, lists, exports, checks) versus read-to-modify (fetch, change, .save()) — the classification decides the tool. 2) For read-to-display paths, add .lean(): Mongoose skips building full document instances with change tracking and returns plain JavaScript objects — meaningfully faster and lighter, especially on lists. 3) Before converting, check what model features the path actually relies on: virtuals, getters, and instance methods disappear with lean — enable lean's virtuals option or compute the value explicitly, consciously, not by surprise. 4) Never mix the modes: a lean result cannot be saved; if a path sometimes edits, it stays a full document query — correctness beats the optimization. 5) Combine with field selection (.select()) so heavy read paths fetch only the fields the response sends — lean cuts hydration cost, select cuts transfer cost, together they make list endpoints cheap. If unsure whether some downstream code mutates the result, trace its usage before converting. Only apply lean once the path is confirmed read-only, and explain why the query needed plain data rather than a live document — not just that lean is 'faster'.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #970\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}