{"success":true,"name":"read-mongodb-duplicate-key-errors-as-design-signals-not-nois","description":"Hitting E11000 duplicate key errors from MongoDB inserts or upserts","category":"ai-brimind","path":"ai-brimind/read-mongodb-duplicate-key-errors-as-design-signals-not-nois/SKILL.md","file":"SKILL.md","content":"---\nname: read-mongodb-duplicate-key-errors-as-design-signals-not-nois\ndescription: \"Hitting E11000 duplicate key errors from MongoDB inserts or upserts\"\n---\n\n# Read MongoDB Duplicate-Key Errors as Design Signals, Not Noise\n\n## When to use\nProject uses MongoDB, and inserts/upserts throw E11000 errors, or uniqueness rules exist only in application code.\n\n## Example request\nCatching E11000 and just logging it → the error IS the business event 'email already registered'; map it to a proper 409/user message. Checking uniqueness with a find before insert → two simultaneous requests both pass the check; only the unique index is race-proof. Mongoose unique:true 'not working' → unique is an index instruction, not a validator; the index must actually exist (and build) on the collection. E11000 on a field that shouldn't be unique → a leftover index from old code; audit indexes, don't work around them. Each maps to 'uniqueness lives in the index — errors from it deserve translation, not suppression'.\n\n## Instructions\nAct as a developer who treats uniqueness as a database-enforced contract and E11000 as that contract speaking. Around unique constraints on MongoDB: (1) enforce uniqueness with a UNIQUE INDEX, never with check-then-insert application logic — the check has a race window between the find and the insert that concurrent requests will eventually hit; the index has none, (2) know the Mongoose subtlety: unique:true in a schema is not validation, it merely requests index creation — confirm the index truly exists on the collection (and note it can't build if duplicate data already exists; clean first), (3) handle E11000 as a first-class business outcome: catch it specifically (error code 11000), translate it to the domain meaning ('username taken', 'already processed') and the right API response, rather than a generic 500 or silent log, (4) for optional-but-unique fields (nullable emails), use a partial unique index so multiple missing values don't collide, (5) when E11000 appears on an unexpected field, investigate the collection's actual indexes before patching code — a stale index is a finding. Only consider uniqueness handled once the index exists, duplicates in flight are proven safe, and the error path speaks the business language — and explain why concurrency can no longer create the duplicate the rule forbids.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1159\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}