I am using node js $http to handle http post request that authenticate the user by mail and password with the DB (mongoDB).
The problem is that the DB query takes time and therefore not sync with the http call. I am returning back http with req==undefiend because I am not waiting (with promise or something like that, to the db query to finish).
Since I am new to JS and node JS I will appreciate if someone could help me fix my code. Thanks!
Important: it will work if I will send the req with true or false value straight from the inner function --> I know that! but.. I want it be written in a more generic way - I want the http logic not involved with the db logic.
app.post('/authenticate_user', function(req, res){
var mail = req.body.Mail;
var password = req.body.Password;
res.setHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0");
var isValid=authenticate_user(mail, password);
console.log("isValid-->"+isValid);
// I get undefiend since at this time the db did nor finish...
res.json(isValid);
});
var authenticate_user=function(mail, password){
var query = user_details.find({'Mail': mail});
query.exec( function(err, docs){
if (docs.length==0) {
return false;
}
else{
return(docs[0].Password==password);
}
});
}