Solvedmongoose Handle cast error on find when objectId is invalid

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
I'm trying to find an item by its _id, but when I try to handle the possible "error", when the client sends an id that doesn't exist and then return it as an user friendly error, it's getting into the "catch" function and resulting in an Error 500 to the user with a very big error message.

I tried to find a method to handle it on google and even here, but I didn't find anything.

If the current behavior is a bug, please provide the steps to reproduce.

ToDo.findById(todoId)
.then(result => {
    return httpResponse.success(res, "Data successfully fetched", result)
})
.catch(err => {
    // When the ID isn't valid, it shows up as an error
    return httpResponse.error(res, err, "Error while fetching the ToDo data on the database");
})

What is the expected behavior?
I want to handle this kind of "error" that for me isn't an error. It's just an invalid item to search.

Please mention your node.js, mongoose and MongoDB version.
Node: v7.4.0
Mongoose: 4.10.5
MongoDB: v3.4.4

31 Answers

✔️Accepted Answer

This is expected behavior and your way of handling the error is mostly correct. I'd recommend instead doing:

.catch(err => {
    if (err.message instanceof mongoose.Error.CastError)
        return httpResponse.success(res, "Data was not found", null);

    return httpResponse.error(res, err, "Error while fetching the data on the database");
})

Checking for instanceof CastError is more robust because the error message may change.

If you don't want to execute this check for every find operation you can use error handling middleware to transform the error into something that is appropriate for your application.

Other Answers:

Yes, I can do that. I'm already doing something similar actually. But, I don't know... For me, a better approach for those cases would be returning an empty user instead of throwing an error.

This is my currently approach:

ToDo.findOne({ _id: todoId, createdBy: userId })
.populate(['createdBy', 'updatedBy'])
.then(result => {
    if (!result) return httpResponse.wrong(res, statusCode.error.NOT_FOUND, `Data was not found`);
        
    return httpResponse.success(res, "Data successfully fetched", result)
})
.catch(err => {
    if (err.message.indexOf('Cast to ObjectId failed') !== -1)
        return httpResponse.success(res, "Data was not found", null);

    return httpResponse.error(res, err, "Error while fetching the data on the database");
})

Related Issues:

360
mongoose Deprecation Warning
I solved that warning doing Right before calling mongoose.connect I'm getting this warning after I d...
119
mongoose Saving a model fails with mongo error: MongoError: Unknown modifier: $pushAll
Well that's one problem mongodb 3.5 is an unstable dev release and should not be used ...
69
mongoose Is not a function ERROR - this.isModified is not a function
You are using an arrow operator for the callback which changes the scope of this If you define a reg...
39
mongoose No retries are made after "failed to connect on first connect"
For anyone wanting auto-reconnection when first connect fails By default mongoose throws an Error if...
34
mongoose Need to check if password field has been modified in pre findOneAndUpdate
I'm currently using this solution and it works You don't need to execute another query. ...
28
mongoose Allow import { model } from mongoose
+1 Currently this doesn't work: It's common when user wants to import variables from module without ...
21
mongoose the options [user] and [pass] is not supported when using with useMongoClient: true
Working on getting support for this in the mongodb driver with the above PR ☝️ For now as a workarou...
19
mongoose Property 'Buffer' does not exist on type 'typeof globalThis'.
Think explicitly adding @types/node should work as a temp workaround npm i --save-dev @types/node@^1...
18
mongoose server/replset/mongos options are deprecated => documentation?
The message says that all of the server replset and mongos options have been moved to the top level ...
12
mongoose Way to handle mongoose.connect() error in promise catch handler
Use the callback of mongoose.connect to catch any error during the connection You can start you serv...
6
mongoose Handle cast error on find when objectId is invalid
This is expected behavior and your way of handling the error is mostly correct Do you want to reques...
5
mongoose mongoose 5.4.20 does not overwrite all properties in a nested subdocument.
I have the same problem using Object.assign() Do you want to request a feature or report a bug? Bug ...