Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB find doesn't return an error if a record doesn't exist?

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.

like image 350
Vegan Sv Avatar asked Jun 09 '16 15:06

Vegan Sv


1 Answers

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
        }
    }
});
like image 200
styvane Avatar answered Oct 23 '22 04:10

styvane