简体   繁体   中英

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!

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.

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
    }
  }
});

To get the solution check following things. 1. Check model name which you have defined or the name of the folder where all your models are present must be right because in my case in models folder where i have defined all my models i was using different model name so as there was no model named that, thats'y i was getting the error. 2. Check Schema name or folder name where it is located.

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