I've had an issue I've been racking my brain (and my googling fingers) with and it's in regard to middleware and express.js.
What I'm essentially trying to do is check if an email is currently in use in my MongoDB database (the check works fine) and if the email address exists, to not continue with my post route and create an account. My flash message works just fine, however my code after doesn't prevent the account from being created still.
I know I can just add the email to an index in my User Schema and call it a day, but it's bugging me not knowing how to do it this other way.
Is it possible, for lack of better coding knowledge, to just say, if email exists, then exit entire router.post, tell user email is in use - without then going on and executing the function(req, res) which creates the account regardless of the email error?
Here is my code for the middleware I'm using to check if the email is already being used.
middlewareObj.checkEmailExist = function(req, res, next){
//Converts user entered email to lowercase
var lowercaseEmail = req.body.email.toLowerCase();
//looks for user entered email in database
User.find({"email": lowercaseEmail}, function(err, user){
if(user.length!=0) {
req.flash("error", "Email already exists, please enter a different email address");
return res.redirect("/register");
}
});
return next();
};
And here is the code for the /register POST route:
router.post("/register", middleware.usernameToLowerCase, middleware.checkSignupForm, middleware.checkEmailExist, function(req, res){
var newUser = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
username: req.body.username
});
User.register(newUser, req.body.password, function(err, user){
if(err){
//For Standard error message or if not included in specific messages below
console.log("error", err.message);
return res.redirect("/register");
}
passport.authenticate("local")(req, res, function(){
req.flash("success", "Welcome To Our Community " + user.firstName + "." + "Your Username Is: " + user.username);
res.redirect("/featured");
});
});
});
You can ignore the other middleware being called prior, that is just for formatting for my database.
I've tried doing the return next(err); but it still just creates the account while also giving me a "Can't set headers after they are sent" error due to the rest of the function being called.
This is my first post, so hopefully I didn't make things too confusing. Let me know if you need additional info/context and I'd be happy to provide.
Thanks in advance!
In your middleware function you are looking up the database which is asynchronous. In the meantime you have gone on to call return next() before the callback is called.
Try to move the return next() in the middleware to and else block of if(user.length!=0) in User.find