{"success":true,"name":"isolate-tenants-in-mongodb-tenantid-in-every-query-no-except","description":"Building a multi-client app where MongoDB collections hold several customers' data","category":"ai-brimind","path":"ai-brimind/isolate-tenants-in-mongodb-tenantid-in-every-query-no-except/SKILL.md","file":"SKILL.md","content":"---\nname: isolate-tenants-in-mongodb-tenantid-in-every-query-no-except\ndescription: \"Building a multi-client app where MongoDB collections hold several customers' data\"\n---\n\n# Isolate Tenants in MongoDB — tenantId in Every Query, No Exceptions\n\n## When to use\nProject uses MongoDB, and documents from multiple tenants/clients/organizations share the same collections.\n\n## Example request\nOne forgotten tenantId filter on a list endpoint → client A sees client B's orders; a data breach from one missing line. Adding the filter manually in every query → humans forget; a Mongoose plugin or query helper injects it automatically. tenantId not in the compound indexes → every tenant's query scans all tenants' data; tenantId belongs FIRST in the index. Deletes and updates without the tenant filter → cross-tenant destruction, worse than cross-tenant reads. Each maps to 'tenant isolation must be enforced by mechanism, not by memory'.\n\n## Instructions\nAct as a security architect who treats one missing tenant filter as a full data breach, because it is. In any shared-collection multi-tenant MongoDB design: (1) make tenantId a required, indexed field on every tenant-owned document, validated at write time, (2) do not rely on developers remembering the filter — enforce it with a mechanism: a Mongoose plugin adding tenantId to every query via middleware, a repository layer whose methods require a tenant context, or schema-level defaults tied to the authenticated session; name the pattern (query scoping / row-level isolation), (3) put tenantId FIRST in compound indexes so each tenant's queries only touch their slice, (4) audit the dangerous verbs hardest: updateMany, deleteMany, and aggregations ($lookup stages also need the tenant match), (5) write at least one test that proves tenant A cannot read or modify tenant B's documents through any endpoint. If the tenancy model (shared collections vs database-per-tenant) is not decided, raise it as a strategic decision before coding. Only proceed once isolation is enforced by code structure, and explain why forgetting is no longer possible, not just discouraged.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1143\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}