Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js and mongoose (mongodb) error cannot read property '' of null

I have a findOne query, and when ever i verify if it returned a empty document i get thrown a error saying 'cannot read property 'username' of null'. That happend when i try to acess doc.username in if(!doc.username) {

My code:

function checkAccDb(username, password) { console.log(2);
    /* Check if accounts exists in db */
    db.findOne({username: username}, function(err, doc){ console.log(3);
        if(err) throw err;

        if(!doc.username) {
            add2stack(username, password);
        }
        else if(doc.status == 200) {
            end(username, password, 1000);
        }
        else if(doc.status == 401) {
            if(doc.password == password)
                end(username, password, 401);
            else
                add2stack(username, password);
        }
        else {
            add2stack(username, password);
        }
    });
}

Could anyone please explain me what's happening here?

Thanks!

like image 393
herenow Avatar asked Oct 13 '12 05:10

herenow


2 Answers

The query succeeds but doesn't find any matches, so both err and doc are null. You need to check if doc is null and handle that case appropriately.

like image 121
Peter Lyons Avatar answered Nov 17 '22 12:11

Peter Lyons


A typical implementation would be like this

db.findOne({username: username},function(err, doc) {
  if (err) {
    // handle error
  }
  if(doc != null)
  {
    if(!doc.username)
    {
        //handle case
    }
    else
    {
        //handle case
    }
  }
});
like image 21
almypal Avatar answered Nov 17 '22 12:11

almypal