Reputation: 1640
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?
Upvotes: 1
Views: 473
Reputation: 16056
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...
});
Upvotes: 2