Node.js 和 mongoose (mongodb) 错误无法读取 null 的属性“”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12870419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js and mongoose (mongodb) error cannot read property '' of null
提问by herenow
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) {
我有一个 findOne 查询,当我验证它是否返回一个空文档时,我会抛出一个错误,提示“无法读取 null 的属性“用户名”。当我尝试在 if(!doc.username) { 中访问 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!
谢谢!
回答by Peter Lyons
The query succeeds but doesn't find any matches, so both errand docare null. You need to check if docis null and handle that case appropriately.
查询成功但未找到任何匹配项,因此err和doc均为空。您需要检查是否doc为空并适当处理这种情况。
回答by almypal
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
}
}
});
回答by Sudhanshu Gaur
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.
要获得解决方案,请检查以下事项。1.检查您定义的模型名称或所有模型所在文件夹的名称必须正确,因为在我的情况下,在模型文件夹中我定义了所有模型我使用了不同的模型名称,因此没有模型命名为,那是我收到错误。2. 检查其所在的架构名称或文件夹名称。

