{"success":true,"name":"know-which-mongoose-hooks-your-mongodb-write-path-actually-f","description":"Using Mongoose middleware/hooks and mixing save with update queries","category":"ai-brimind","path":"ai-brimind/know-which-mongoose-hooks-your-mongodb-write-path-actually-f/SKILL.md","file":"SKILL.md","content":"---\nname: know-which-mongoose-hooks-your-mongodb-write-path-actually-f\ndescription: \"Using Mongoose middleware/hooks and mixing save with update queries\"\n---\n\n# Know Which Mongoose Hooks Your MongoDB Write Path Actually Fires\n\n## When to use\nProject uses Mongoose on MongoDB, and schemas have pre/post hooks (hashing, timestamps, side effects) while code uses various write methods.\n\n## Example request\nPassword hashing in pre('save') but the reset flow uses updateOne → the new password is stored in plain text; update queries never fire save hooks. pre('updateOne') expecting this to be the document → in query middleware, this is the QUERY, not the doc; a classic silent bug. Validation skipped on updates → runValidators is off by default for update queries; enable it or validate at the route. findByIdAndUpdate bypassing business logic in save hooks → either move logic to a service function all paths call, or standardize the write method. Each maps to 'hooks are bound to specific methods — every write path must be checked against them'.\n\n## Instructions\nAct as a developer who audits which middleware runs on which write path before trusting any Mongoose hook. When schemas carry pre/post middleware: (1) list every way the app writes that model — save, create, updateOne, findOneAndUpdate, insertMany, bulkWrite — and mark which hooks each one actually triggers, because document middleware (save) and query middleware (updateOne, findOneAndUpdate) are separate systems and do not cover each other, (2) for critical logic (password hashing, computed fields, audit stamps), either register the matching hook for EVERY write method used, or better: move the logic into one service-layer function that all write paths must call — mechanism over memory, (3) know the context rule: in query middleware this is the query object (use this.getUpdate()), not the document — never assume document access, (4) remember update queries skip schema validation unless runValidators: true is set. When a field 'sometimes' misses its processing, suspect a bypassing write path FIRST. Only trust the hook once every write route is confirmed covered, and explain which mechanism guarantees the logic runs regardless of how the write happens.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1148\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}