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