Node.js和mongoose(mongodb)错误无法读取null属性

我有一个findOne查询,当我validation,如果它返回一个空白的文档,我会抛出一个错误,说'不能读取属性'用户名'null'。 当我尝试访问doc.username 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); } }); } 

任何人都可以请解释我在这里发生了什么?

谢谢!

查询成功,但没有find任何匹配,所以errdoc都是空的。 您需要检查doc是否为空,并适当地处理该情况。

一个典型的实现将是这样的

 db.findOne({username: username},function(err, doc) { if (err) { // handle error } if(doc != null) { if(!doc.username) { //handle case } else { //handle case } } }); 

要得到解决scheme检查下面的东西。 1.检查您定义的模型名称或所有模型所在的文件夹的名称必须正确,因为在我的模型文件夹中,我已经定义了所有模型我使用了不同的模型名称,因此没有模型命名,那是我得到错误。 2.检查它所在的架构名称或文件夹名称。