{"record":{"id":"d5745af3a2037faf","repo":"RocketChat/Rocket.Chat","slug":"error-failed-to-delete-department","errorCode":"error-failed-to-delete-department","errorMessage":"error-failed-to-delete-department","messagePattern":"error-failed-to-delete-department","errorType":"error_code","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"apps/meteor/server/lib/omnichannel/departmentsLib.ts","lineNumber":225,"sourceCode":"\t// Visitor is already validated at this point\n\treturn LivechatVisitors.updateDepartmentById(visitorId, department);\n}\n\nexport async function removeDepartment(departmentId: string) {\n\tlivechatLogger.debug({ msg: 'Removing department', departmentId });\n\n\tconst department = await LivechatDepartment.findOneById<Pick<ILivechatDepartment, '_id' | 'businessHourId' | 'parentId'>>(departmentId, {\n\t\tprojection: { _id: 1, businessHourId: 1, parentId: 1 },\n\t});\n\tif (!department) {\n\t\tthrow new Error('error-department-not-found');\n\t}\n\n\tconst { _id } = department;\n\n\tconst ret = await LivechatDepartment.removeById(_id);\n\tif (ret.acknowledged !== true) {\n\t\tthrow new Error('error-failed-to-delete-department');\n\t}\n\n\tconst removedAgents = await LivechatDepartmentAgents.findByDepartmentId(department._id, { projection: { agentId: 1 } }).toArray();\n\n\tconst actions = ['Removing department agents', 'Unsetting fallback department', 'Removing department from rooms'];\n\tlivechatLogger.debug({\n\t\tmsg: 'Post department removal actions',\n\t\tdepartmentId: _id,\n\t\tactions,\n\t});\n\n\tconst promiseResponses = await Promise.allSettled([\n\t\tLivechatDepartmentAgents.removeByDepartmentId(_id),\n\t\tLivechatDepartment.unsetFallbackDepartmentByDepartmentId(_id),\n\t\tLivechatRooms.bulkRemoveDepartmentAndUnitsFromRooms(_id),\n\t]);\n\n\tpromiseResponses.forEach((response, index) => {","sourceCodeStart":207,"sourceCodeEnd":243,"githubUrl":"https://github.com/RocketChat/Rocket.Chat/blob/b2c16d5842cbe6b69b59bdf6fc5e5f1afcd1f0b0/apps/meteor/server/lib/omnichannel/departmentsLib.ts#L207-L243","documentation":"Thrown by `removeDepartment` when `LivechatDepartment.removeById(_id)` returns a write result with `acknowledged !== true`. This is a MongoDB driver-level outcome: the deleteOne was not acknowledged by the server (unacknowledged write concern, connection drop mid-write, or driver error surfaced through the result rather than an exception).","triggerScenarios":"MongoDB connection instability at the moment of the delete, a write concern configured without acknowledgement (w: 0), or a driver/server version quirk returning acknowledged:false — the department lookup succeeded, so the document existed an instant earlier.","commonSituations":"Self-hosted MongoDB behind flaky networking; replica set step-down during the delete; aggressive connection-pool recycling; custom write-concern settings.","solutions":["Retry `removeDepartment` after verifying the department still exists (the delete may or may not have landed)","Check MongoDB health and write concern configuration (avoid w:0 for control-plane writes)","Inspect server logs/mongod for the write outcome; if the document persists, retry usually succeeds once the connection stabilizes"],"exampleFix":"// before\nawait removeDepartment(depId);\n\n// after\nfor (let attempt = 1; attempt <= 3; attempt++) {\n  try {\n    await removeDepartment(depId);\n    break;\n  } catch (e) {\n    if (e.message !== 'error-failed-to-delete-department' || attempt === 3) throw e;\n    await LivechatDepartment.findOneById(depId, { projection: { _id: 1 } }).then((d) => !d && break);\n  }\n}","handlingStrategy":"retry","validationCode":"// Not a payload problem — pre-check connection health instead\nconst ping = await LivechatDepartment.findOneById(depId, { projection: { _id: 1 } });\nif (!ping) return; // already gone — nothing to delete","typeGuard":null,"tryCatchPattern":"let lastErr: unknown;\nfor (let i = 0; i < 3; i++) {\n  try {\n    await removeDepartment(depId);\n    lastErr = undefined;\n    break;\n  } catch (e) {\n    if (e instanceof Error && e.message !== 'error-failed-to-delete-department') throw e;\n    lastErr = e;\n  }\n}\nif (lastErr) throw lastErr;","preventionTips":["Use acknowledged write concerns (never w:0) for control-plane deletes","Monitor MongoDB connectivity; unacknowledged writes cluster with connection flaps","Verify post-retry that the department actually disappeared"],"tags":["omnichannel","departments","mongodb","write-concern","delete"],"backgroundTag":"database-write-unacknowledged","analyzedSha":"b2c16d5842cbe6b69b59bdf6fc5e5f1afcd1f0b0","analyzedAt":"2026-08-18T15:26:39.429Z","contentChangedAt":"2026-08-18T15:26:39.429Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}