I am rookie in node and mongodb, so I do not know how to get this data. I always get undefined, I have read that it is because is async and I know is duplicated, but I can't figure it out.
I have created a function that console log the result but I can't set a var inside this function, just console log the value.
This is the function that make the connection to database
var findUser = function (mail) {
MongoClient.connect(url, function (err, db) {
if(err) {
console.log('ha habido un problema al conectar', err);
} else {
console.log('connected');
var collection = db.collection('users')
.find({email : mail}).toArray(function (err, result) {
if (err) {
finded(err);
} else if(result.length) {
finded(result);
} else {
finded(false);
}
db.close;
});
}
});
};
and this is the one that receive the data
var finded = function(findedUser){console.log(findedUser)};
but I want to have that data in a variable so I can read it something like
var finded = function(findedUser){user = findedUser};
where user is a global variable so I can use it something like if(user.lenght)
Update
I hate when I find a question and there is no the final response, so what I finally did was create a promise and wrap all inside of it, like this:
function findUserPromise(mail) {
return new Promise(function(resolve, reject) {
MongoClient.connect(url, function (err, db) {
if(err) {
console.log('ha habido un problema al conectar', err);
} else {
var collection = db.collection('users')
.find({email : mail}).toArray(function (err, result) {
if (err) {
resolve(err);
} else if(result.length) {
resolve(result);
} else {
resolve(false);
}
db.close;
});
}
});
});
};
and the usage was
findUserPromise(username).then(function(result) {
if (result == false) {
console.log('not finded');
} else {
var decryptPass = decrypt(result[0].password);
if (decryptPass == password) {
done(null, { username: result[0].email, name: result[0].name });
} else {
done(null, null);
}
}
}).catch(function(err) {
err;
});