The problem is that the db.users.find
is an asynchronous function. I'll suggest the following:
app.post("/sign-up", function(req, res){
var validateUser = function(callback) {
db.users.find({email : req.body.email}, function(err, users) {
if( err || !users){
callback(true);
} else {
callback(false);
}
});
}
validateUser(function(isValid) {
if(isValid == true){
db.users.save({
title: req.body.title,
firstname: req.body.firstname,
surname: req.body.surname,
country : req.body.country,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 10)
}, function(err, saved) {
if( err || !saved ) console.log("User not saved");
else console.log("User saved");
res.location("sign-up-success");
// And forward to success page
res.redirect("sign-up-success");
});
}
})
});