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.
}
Short answer: use mongoose.Types.ObjectId.
Mongoose (but not mongo) can accept object Ids as strings and "cast" them properly for you, so just use:
MyClass.findById(req.params.id)
However, the caveat is if req.params.id
is not a valid format for a mongo ID string, that will throw an exception which you must catch.
So the main confusing thing to understand is that mongoose.SchemaTypes
has stuff you only use when defining mongoose schemas, and mongoose.Types
has the stuff you use when creating data objects you want to store in the database or query objects. So mongoose.Types.ObjectId("51bb793aca2ab77a3200000d")
works, will give you an object you can store in the database or use in queries, and will throw an exception if given an invalid ID string.
findOne
takes a query object and passes a single model instance to the callback. And findById
is literally a wrapper of findOne({_id: id})
(see source code here). Just find
takes a query object and passes an array of matching model instances to the callback.
Just go slow. It's confusing but I can guarantee you you are getting confused and not hitting bugs in mongoose at this point. It's a pretty mature library, but it takes some time to get the hang of it.
The other suspect thing I see in your snippet is not using new
when instantiating ChildClass
. Beyond that, you'll need to post your schema code in order for us to help you tract down any CastErrors that remain.
Best Answer
I had faced this same issue sometimes back, for
mongoose
version > 4.7.2I solved it by installing
mongoose
version 4.7.2also, you can change your
package.json
so that it uses this exact version of mongoose.This bug is caused because of
bson
package. which gives the errorRead more about it in this link.
This bug started when
mongoose
was updated from version4.7.2
to4.7.3
. You can update to newer version ofmongoose
when this bug is solved. You can track the bug here and here.So, Finally you can solve this error by installing mongoose version 4.7.2