I have a username field and an email field on signup and I want to check if they exist before adding the user to the database. Most examples for passport only look up one field like username and I cant figure out how to look up 2. If I do what I have below and the user enters an existing username but a non-existing email it would go through and if the user enters an existing email but a non-existing username it would go through because their is no username.
I know why that is happening. I just can't figure out how to put the 2 queries together so it saves it only after it sees that there is no username and or no email. To be clearer, there should be no duplicates of usernames and emails.
I was thinking maybe setting a variable in the else statement saying that it is ok to save the user and later in the code check to see if there are 2 of these variables and if there are those variables then save but I don't know how to do that. I think it would be hard since the queries are asynchronous. I wish I could do that method.
and how would I deal with the connect-flash messages?
passport.use("local-signup", new LocalStrategy({
usernameField : "email",
passwordField : "password",
passReqToCallback : true
},
function(req, email, password, done){
User.findOne({"email" : email}, function(err, user){
if(err) return done(err);
if(user){
return done(null, false, req.flash("signupMessage", "That email is already taken"))
}else{
var newUser = new User();
newUser.username = req.body.username;
newUser.password = password;
newUser.email = req.body.email;
newUser.save(function(err, doc){
if(err) throw err;
console.log("doc", " " , doc)
return done(null, newUser);
})
}
})
console.log("username " + req.body.username)
User.findOne({"username" : req.body.username}, function(err, user){
if(err) return done(err);
if(user){
return done(null, false, req.flash("signupMessage", "that username is taken"))
}else{
var newUser = new User();
newUser.username = req.body.username;
newUser.password = password;
newUser.email = req.body.email;
newUser.save(function(err, doc){
if(err) throw err;
console.log("doc", " " , doc)
return done(null, newUser);
})
}
})
}
))