如何将callback返回值分配给Mongoose中的variables?
我正在使用mongoose.find()
函数来检查用户的凭据。
findUser
函数将从.find()
接收error
和data
参数。
我想存储一个variables, .find()
方法find了与查询匹配的东西。
相反,我的console.log(logged)
显示了很多关于MongoDB操作的查询信息。
var logged = UserModel.find( { username: username, password: password}, findUser ); console.log(logged); var findUser = function (err, data) { (data.length) ? return true : return false; };
如何从mongoose.find()
方法返回true或false ?
请记住,nodejs是asynchronous非io阻塞,所以任何数据库操作将运行asynchronous,可能你的variables将不会被指定为你想要的。
我喜欢在我的stream量控制中使用承诺,在我的情况下,我使用蓝鸟这是一个非常酷的承诺库,你可以做这样的事情(假设在这里expression):
var BPromise = require('bluebird'), mongoose = BPromise.promisifyAll(require('mongoose')); // etc etc load your model here //--------------------------------- var thiz = this; thiz.logged = false; var myPromises = []; myPromises.push( UserModel.find({ username: username, password: password}).execAsync().then(function(data){ thiz.logged = (data.length>0); }) );
//等待所有的承诺完成,以防万一你有多个
BPromise.all(myPromises).then(function(){ // do whatever you need... });