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?
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With