{"id":691,"hash":"077e8c04d6fd86f147d48f37b61e1d56d01ce623c8ab4a1c994fbc21641eda15","pattern":"What&#39;s Mongoose error Cast to ObjectId failed for value XXX at path &quot;_id&quot;?","full_message":"When sending a request to /customers/41224d776a326fb40f000001 and a document with _id 41224d776a326fb40f000001 does not exist, doc is null and I'm returning a 404:\n\n  Controller.prototype.show = function(id, res) {\n    this.model.findById(id, function(err, doc) {\n      if (err) {\n        throw err;\n      }\n      if (!doc) {\n        res.send(404);\n      }\n      return res.send(doc);\n    });\n  };\n\nHowever, when _id does not match what Mongoose expects as \"format\" (I suppose) for example with GET /customers/foo a strange error is returned:\n\n  CastError: Cast to ObjectId failed for value \"foo\" at path \"_id\".\n\nSo what's this error?","ecosystem":"npm","package_name":"mongodb","package_version":null,"solution":"Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the matching doc.  This is an ObjectId but \"foo\" is not a valid ObjectId so the cast fails.\n\nThis doesn't happen with 41224d776a326fb40f000001 because that string is a valid ObjectId.\n\nOne way to resolve this is to add a check prior to your findById call to see if id is a valid ObjectId or not like so:\n\nif (id.match(/^[0-9a-fA-F]{24}$/)) {\n    // Yes, it's a valid ObjectId, proceed with `findById` call.\n}","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/14940660/whats-mongoose-error-cast-to-objectid-failed-for-value-xxx-at-path-id","votes":214,"created_at":"2026-04-19T04:51:30.402679+00:00","updated_at":"2026-04-19T04:51:30.402679+00:00"}