Node.js 函数从数据库返回数据
我是NodeJS的新手,我的模型使用mongoose 我有一个函数namde check,它有一个isnamether函数,它接收名称字符串作为参数。它检查数据库并查找提供的名称字符串(如果用户以该名称存在),this.isnamether将返回trueNode.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:
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
...
}
});
毕竟,它是任意时间的,所以您将不会得到任何同步返回值
还有另一种方式:承诺。供您签出的一些库: