I'm using Mongoose:
user.find({username: 'xyz'}, function(err, doc){
if(err){
res.render('error', {errorMsg: "Error blah blah"})
}
});
I'm deliberately using a user who doesn't exist xyz and it's not triggering any errors, I thought it was because of Mongoose but then I tried in MongoDB shell and yes MongoDB won't return an error if a record doesn't exist.
>db.accounts.find({username: 'xyz'})
> // no error, blank line
How do I handle that? I want the execution of the script stop if a user doesn't exist.
Well, if the "username" doesn't exist, that doesn't mean there is an error. Instead you should do something like this.
user.find({ username: 'xyz' }, function(err, doc){
if(doc.length === 0 || err){
res.render('error', { errorMsg: "Error blah blah" } )
}
});
Or more verbose version:
user.find({ username: 'xyz' }, function(err, doc) {
if(err){
res.render('error', { errorMsg: "Error blah blah" } )
} else {
if (doc.length === 0) {
console.log("User doesn't exist");
} else {
//do something
}
}
});
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