简体   繁体   中英

How to assign callback return value to a variable in Mongoose?

I'm using mongoose.find() function to check the user's credentials.

The findUser function will receive, from the .find() , error and data arguments.

I want to store on a variable wether the .find() method has found something that matches the query or not.

Instead, my console.log(logged) is displaying a lot of query information about the MongoDB operation.

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?

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.

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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