I have a problem in validating user name and password in nodejs and mongodb . Below is the code what i tried. Password validation not working. what i am doing wrong here...
server.get('/login', function(req, res)
{
var status=""
user.findOne({name: req.query.username}, function(err, users)
{
if( err || !users)
{
console.log("No users found");
status="failed"
}
else
{
if(password==req.query.password)
{
status="success"
}
else
{
status="failed"
}
}
});
res.send(status);
});
Node.js runs on an asynchronous event loop, which means that your code won't necessary run the way you may always think it will (synchronously). To overcome this issue, there are a couple options: callbacks, or promises. Promises are generally the preferred route, and there are a couple libraries which I suggest: bluebird (is awesome) or async (which I haven't used a lot, but many prefer it).
If you'd like to work without promises for right now, you could fix your issue this way:
user.findOne({name: req.query.username}, function(err, users) {
if( !err && users && password === req.query.password ) {
res.send({ status: 'success' });
}
else { res.send({ status: 'failed' }); }
});
Again, the reason your code is not working is because the event loop reaches your res.send(status)
before the database query has been resolved. My suggestion should work fine for you, but as your processes become more complex, I would look into promises to resolve any further async issues.