{"success":true,"name":"distinguish-missing-null-and-empty-fields-in-mongodb-queries","description":"Querying MongoDB fields that may be absent, null, or empty","category":"ai-brimind","path":"ai-brimind/distinguish-missing-null-and-empty-fields-in-mongodb-queries/SKILL.md","file":"SKILL.md","content":"---\nname: distinguish-missing-null-and-empty-fields-in-mongodb-queries\ndescription: \"Querying MongoDB fields that may be absent, null, or empty\"\n---\n\n# Distinguish Missing, Null, and Empty Fields in MongoDB Queries\n\n## When to use\nProject uses MongoDB, and a query filters on a field that some documents don't have or hold as null.\n\n## Example request\nfind({ phone: null }) → matches BOTH documents where phone is null AND documents missing the field entirely; often not what you meant. Checking 'field exists' with truthiness in JS after fetching → $exists: true does it in the query. 'Field has a real value' → { phone: { $ne: null, $exists: true } } or $type narrows it precisely. Schemaless drift: some docs have '', some null, some nothing → three different states your code treats as one; decide the canonical 'empty' and migrate. Each maps to 'in a schemaless store, absence has three spellings — queries must name which one they mean'.\n\n## Instructions\nAct as a developer who knows that in MongoDB 'no value' comes in three forms — field missing, field null, field empty ('' or []) — and that queries treat them differently. When filtering on optional fields: (1) state which of the three states the logic actually cares about, (2) use the precise operator: $exists for presence of the key, null equality for missing-or-null (and know it matches both), $type to require an actual type, $ne combinations for 'has a real value', and for arrays remember { arr: [] } vs $size: 0 vs $exists, (3) when you discover documents storing the same 'empty' concept in multiple spellings, treat it as schema drift: pick one canonical representation, enforce it at the write boundary (schema default or validation), and migrate the strays — do not scatter three-way checks across every query, (4) in Mongoose, know that undefined fields are simply not saved, so defaults and required flags shape which state new documents get. If the intended semantics of an optional field are undocumented, ask or define them. Only write the filter once the targeted state is named, and explain why the query matches exactly the documents the business rule means.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1145\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}