{"success":true,"name":"make-mongodb-upserts-correct-with-setoninsert","description":"Using upsert:true in a MongoDB update and setting initial fields","category":"ai-brimind","path":"ai-brimind/make-mongodb-upserts-correct-with-setoninsert/SKILL.md","file":"SKILL.md","content":"---\nname: make-mongodb-upserts-correct-with-setoninsert\ndescription: \"Using upsert:true in a MongoDB update and setting initial fields\"\n---\n\n# Make MongoDB Upserts Correct With $setOnInsert\n\n## When to use\nProject uses MongoDB, and an update runs with upsert:true where new and existing documents need different treatment.\n\n## Example request\nUpsert setting createdAt with $set → every later update overwrites creation time; $setOnInsert writes it only when inserting. Counters via upsert → $inc works for both paths: initializes to the increment on insert, adds on update. Two requests upserting the same key simultaneously → without a unique index on the filter field, both can insert; the unique index makes upsert race-safe. Filter fields quietly copied into the new doc → upsert builds the insert from the filter's equality fields; know that, or get surprise fields. Each maps to 'upsert is two operations in one — insert-only values need insert-only operators'.\n\n## Instructions\nAct as a developer who splits every upsert mentally into its two outcomes — 'it inserted' and 'it updated' — and checks the write is correct for BOTH. When writing upsert:true updates on MongoDB: (1) separate the fields: values that must exist only at creation (createdAt, initial status, defaults) go in $setOnInsert; values refreshed every time (updatedAt, latest data) go in $set; accumulating values use $inc which handles both paths naturally, (2) know how the inserted document is born: equality conditions from the filter are copied into it — verify that's desirable, (3) make concurrent upserts safe: two simultaneous upserts with the same filter can BOTH insert unless a unique index exists on the filter's key field — for any 'find-or-create by key' logic, the unique index is part of the design, plus handling the duplicate-key error as 'retry as update', (4) test both branches explicitly: run it against a missing key and an existing key and inspect both resulting documents. If it's unclear which fields are creation-only, ask the spec. Only ship the upsert once both outcomes are verified document-by-document, and explain why neither path corrupts the other's fields.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1151\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}