What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

mongodb, mongoose

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.

This doesn't happen with `41224d776a326fb40f000001` because that string is a valid `ObjectId`.

One 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:

if (id.match(/^[0-9a-fA-F]{24}$/)) {
    // Yes, it's a valid ObjectId, proceed with `findById` call.
}

Problem

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`: ``` Controller.prototype.show = function(id, res) { this.model.findById(id, function(err, doc) { if (err) { throw err; } if (!doc) { res.send(404); } return res.send(doc); }); }; ``` However, when `_id` does not match what Mongoose expects as "format" (I suppose) for example with `GET /customers/foo` a strange error is returned: CastError: Cast to ObjectId failed for value "foo" at path "_id". So what's this error?

Original source

Related problems