0

I am new to nodejs and mongodb please help!

I am fetching two values from a sample login page and based on the email id, I am searching through the collection to check if the password matches

This is the js file making the call for validating

exports.profile = function(req, res) {

var email=req.body.email;
var password=req.body.password;
var validUser=validate.isValidUser(email,password);

console.log(validUser);
res.sendfile(path.join(__dirname, '../public', 'profile.html'));};

This is my js file to check if the password matches

exports.isValidUser = function(emailEntered, passEntered) {

var pass;
mongoose.connect('mongodb://localhost/registration');
User.findOne({
    email : emailEntered
}, function(err, doc) {
    if (err) {
        console.log(err);
    } else {

        pass = doc.password;
        console.log(pass);
        console.log(passEntered);

        mongoose.connection.close();
    }

    console.log('Disconnected from server successfully');
});


if (passEntered===pass) {
    return true;
}

else {
    return false;
}};

Every time I run it even if the password matches, it is returning false.

Tanmay Awasthi
  • 69
  • 1
  • 2
  • 8
  • `User.findOne()` is **async**, so it take some time to get the data from DB. The code `if (passEntered===pass) {` is executed before the data from the DB is fetched. i.e. `passEntered === undefined` which is false. – Tushar May 26 '16 at 10:37
  • what should I do to wait for db to return the password? – Tanmay Awasthi May 26 '16 at 10:44
  • Put the `if (passEntered === pass)` code at the end of the `function(err, doc)` block, best into the `else` part – JSchirrmacher May 26 '16 at 10:46
  • Try creating another function, which will be called inside `function(err, doc)` in the `else` part. And do the conditional check inside that function. @TanmayAwasthi – Shrabanee May 26 '16 at 11:52

0 Answers0