{"success":true,"name":"handle-mongodb-objectid-types-explicitly-at-every-boundary","description":"Comparing or querying MongoDB IDs that come from requests or JSON","category":"ai-brimind","path":"ai-brimind/handle-mongodb-objectid-types-explicitly-at-every-boundary/SKILL.md","file":"SKILL.md","content":"---\nname: handle-mongodb-objectid-types-explicitly-at-every-boundary\ndescription: \"Comparing or querying MongoDB IDs that come from requests or JSON\"\n---\n\n# Handle MongoDB ObjectId Types Explicitly at Every Boundary\n\n## When to use\nProject uses MongoDB, and an _id or reference field is compared, queried, or received as a string from outside.\n\n## Example request\nfind({ _id: req.params.id }) returns nothing → the stored _id is an ObjectId, the param is a string; convert with new ObjectId(id). someId === doc._id is always false → ObjectId is an object; use .equals() or compare .toString() on both sides. Invalid id string crashes the route → new ObjectId('abc') throws; validate with ObjectId.isValid() first and return 400. Mixed collections where some ids were saved as strings → now every query needs $in with both forms; fix the data, not every query. Each maps to 'strings and ObjectIds look identical in logs but never match'.\n\n## Instructions\nAct as a developer who assumes every ID crossing a boundary (HTTP param, JSON body, JWT, query string) arrives as a string and every stored MongoDB id is an ObjectId — and that they NEVER match silently. At each boundary: (1) validate first with ObjectId.isValid(value) and reject bad input cleanly instead of letting new ObjectId() throw mid-handler, (2) convert explicitly (new ObjectId(value)) before using it in a filter — note that Mongoose casts for you on schema-typed paths, but raw driver calls and $expr/aggregations do not, (3) compare with id1.equals(id2) or matched .toString() calls, never ===, (4) if you find ids stored inconsistently (some strings, some ObjectIds), treat that as the root cause: plan a data fix rather than patching every query with dual-form matching. When a query 'returns nothing but the data exists', check the id type FIRST before anything else. Only proceed once types at the boundary are confirmed, and explain why the comparison now matches at the type level, not just visually in the logs.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1053\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}