findOne()返回布尔值 - Nodejs

时间:2015-06-18 08:12:12

标签: node.js mongoose

我在使用mongoose的快递js中遇到了问题。 我有一个与模型层通信的管理器层(使用mongoose)。 在管理器层中,我有可以由控制器使用的CRUD功能。 在管理器层中,我有一个函数“checkCredentials()”,它将在MongoDB中搜索给定的用户名和密码,并向控制器返回true或false。 问题是函数“checkCredentials()”返回undefined。 以下是代码,如果有人可以提供帮助,我将非常感激。

function checkCredentials(uName,Pass){      

    librarian.findOne({ UserName: uName , Password: Pass}, function (err, doc){     
        console.log('uName: '+uName);
        console.log('Pass: '+Pass); // this will print on console , working fine

        if (doc === null) {            
            return false; // this will return undefined to the controller

        } else {            
            return true;  // this will return undefined to the controller          
        }
}

2 个答案:

答案 0 :(得分:1)

你不能这样做。 findOne异步工作,而函数需要立即返回值。 所以"返回"你在findOne中写道,它不是函数checkCredentials

的那个

编辑: 如果你想做得对 - 你需要将一个回调函数传递给checkCredentials - 然后当findOne完成时,用你需要的参数执行回调

答案 1 :(得分:1)

function checkCredentials(uName,Pass, callback){      

    librarian.findOne({ UserName: uName , Password: Pass}, function (err, doc){     
        console.log('uName: '+uName);
        console.log('Pass: '+Pass); // this will print on console , working fine
        if(err)
               return callback(err, false);
        if (doc === null) {            
            return callback(null, false); // this will return undefined to the controller

        } else {            
            return callback(null, true);  // this will return undefined to the controller          
        }
}

您可以尝试使用此代码。

相关问题