9

我有一个 findOne 查询,当我验证它是否返回一个空文档时,我会收到一条错误消息,提示“无法读取属性 'username' of null”。当我尝试在 if(!doc.username) {

我的代码:

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

谁能解释一下这里发生了什么?

谢谢!

4

3 回答 3

11

查询成功,但未找到任何匹配项,因此errdoc均为空。您需要检查是否doc为 null 并适当地处理这种情况。

于 2012-10-13T06:39:44.887 回答
2

一个典型的实现是这样的

db.findOne({username: username},function(err, doc) {
  if (err) {
    // handle error
  }
  if(doc != null)
  {
    if(!doc.username)
    {
        //handle case
    }
    else
    {
        //handle case
    }
  }
});
于 2012-10-13T11:48:42.393 回答
0

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.

于 2015-07-23T19:25:15.047 回答