简体   繁体   English

如何在Mongoose中为变量分配回调返回值?

[英]How to assign callback return value to a variable in Mongoose?

I'm using mongoose.find() function to check the user's credentials. 我正在使用mongoose.find()函数来检查用户的凭据。

The findUser function will receive, from the .find() , error and data arguments. findUser函数将从.find()接收errordata参数。

I want to store on a variable wether the .find() method has found something that matches the query or not. 我想在.find()方法是否找到与查询匹配的内容上存储一个变量。

Instead, my console.log(logged) is displaying a lot of query information about the MongoDB operation. 相反,我的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;
};

How can I return a true or false from mongoose.find() method? 如何从mongoose.find()方法返回true或false

Remember that nodejs is async non-io blocking so any database operation will run async and probably your variable won't be assigned as you want. 请记住,nodejs是异步非io阻塞的,因此任何数据库操作都将异步运行,并且可能不会根据需要分配变量。

I like to use promises in my flow control, in my case I use bluebird which is a very cool promise library, you could do something like this (assuming express here): 我喜欢在流控制中使用promise,在我的情况下,我使用bluebird ,这是一个非常酷的promise库,您可以执行以下操作(假设在此处表达):

 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);
        })
    );

//wait for all the promises to complete in case you have more than one //等待所有诺言完成,以防万一

BPromise.all(myPromises).then(function(){
 // do whatever you need...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM