Hello Stackoverflow community, I'm new to Node.js / express and i need your help because i stuck at some problem.
I'm trying to make a registration process where the Post inputs are saved into a mongodb. Before i wanna validate if the users email adress already exists in the database.
If i try to define a var at the db.users.find() statement the app wont work.
app.post("/sign-up", function(req, res){
var validate;
db.users.find({email : req.body.email}, function(err, users) {
if( err || !users){
validate = true;
}else{
validate = false;
}
});
console.log(validate);
if(validate == 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");
});
}
});
how the db.users.find() functions needs to look like that i can make if/else request for the db.users.save() function.
The problem is that the
db.users.find
is an asynchronous function. I'll suggest the following: