CorrieSparrow
CorrieSparrow

Reputation: 531

Proper error handling in mongoose query.exec()

I've digged into Mongoose docs, but I still can't find the information how I should handle errors in query.exec().

var query = User.findOne({_id: userId});

    var promise = query.exec(function(err) {
        if (err) {
            res.json(err);
            return;
        }
    });
    promise.then(function(user) {
        res.json(user.name);
    });

When I pass incorrect userId, I'm getting Unhandled rejection CastError: Cast to ObjectId failed error printed to the console.

I thought that res.json(err) followed by return statement will be enough to handle the error correctly and prevent it from being shown in the console, but it's not. What should I do instead?

Upvotes: 7

Views: 11591

Answers (2)

Sangharsh
Sangharsh

Reputation: 3019

With minimal change to your code:

var query = User.findOne({_id: userId});

    var promise = query.exec(function(err) {
        if (err) {
            res.json(err);
            return Promise.reject(err); // Updated this line
        }
    });
    promise.then(function(user) {
        res.json(user.name);
    });

Using promises properly:

User.findOne({_.id: userId})
  .then(function(user) {
    return res.json(user.name);
  })
  .catch(function(err) {
    return res.json(err);
  });

Upvotes: 1

rsp
rsp

Reputation: 111258

With callback:

var query = User.findOne({_id: userId});
query.exec(function (err) {
    if (err) {
        // handle error
        return;
    }
    // handle success
});

With promise:

var query = User.findOne({_id: userId});
query.exec().then(function () {
    // handle success
}).catch(function (err) {
    // handle error
});

Currently you are mixing both of those styles. Choose one style and stick to it instead.

Upvotes: 14

Related Questions