简体   繁体   中英

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.

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
        }
    }
});
var user = db.accounts.findOne({username: 'xyz'});

if (!user) {
   // handle error
   alert('fail');
}

Try to check if the doc is null or not first and then you can get on with your function.

user.find({ username: 'xyz' }, function(err, doc){
   if(doc === null || err){
      res.render('error', { errorMsg: "Error blah blah" } )
   }
   else {
      do something...
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM