Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 函数从数据库返回数据_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 函数从数据库返回数据

Node.js 函数从数据库返回数据,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我是NodeJS的新手,我的模型使用mongoose 我有一个函数namde check,它有一个isnamether函数,它接收名称字符串作为参数。它检查数据库并查找提供的名称字符串(如果用户以该名称存在),this.isnamether将返回true var check= function() { this.nameIsThere = false; this.isNameThere= function(name){ userModel.find({firstname:

我是NodeJS的新手,我的模型使用mongoose

我有一个函数namde check,它有一个isnamether函数,它接收名称字符串作为参数。它检查数据库并查找提供的名称字符串(如果用户以该名称存在),this.isnamether将返回true

var check= function()
{   

  this.nameIsThere = false;

  this.isNameThere= function(name){

  userModel.find({firstname: name},function(err,result){

                if(result)
                {
                    this.nameIsThere= true;
                }

               })

 return this.nameIsThere;  
 }
 }

即使名称存在,因为异步编程的本质,上面的代码也会返回false。有没有办法在userModel.find执行之后执行返回isNameThere。或任何其他解决方案。谢谢大家

小心分号,你忘了一些。在JavaScript中,最好将左括号放在函数头的旁边,而不是下一行

您可以将DB调用封装在如下函数中:

function checkForName (callback) {
    userModel.find({firstname: name}, callback);
}

checkForName(function (err, result) {
    if (result) {
        nameIsThere = true;
        //do something else
        ...
    }
});
毕竟,它是任意时间的,所以您将不会得到任何同步返回值

还有另一种方式:承诺。供您签出的一些库:


感谢您的回复,在我的问题isName中有一个函数,我正在从其他文件调用此函数,我希望isName返回正确/错误的结果。我要做的主要事情是在userMode.find完成其操作并检查名称是否存在后执行isNameThere的return。我需要返回true或false,这是我的观点。这不是它的工作方式,没有同步方式。您唯一能做的就是使用回调函数作为“isNameThere”函数的参数(请参阅我的代码),并在得到结果时调用该函数。