skip to Main Content
const userRegistrationPost = (req, res) => {
    const{name, email, pass1, pass2} = req.body;

        let errors = [];

        if(!name|| !email || !pass1 || !pass2){
            errors.push({msg: "Please ensure all fields are filled"});
        }

        if(pass1 !==pass2){
            errors.push({msg: "Passwords don't match"});
        }
        
        if(pass1.length < 6){   //line 66
            errors.push({msg: "Passwords must be at least 6 characters"});
        }

        if(errors.length > 0){
            res.render("user_registration", {errors, name, email, pass1, pass2})
        }else{
        //WE DON'T WANT TO HAVE 2 USERS WITH THE SAME EMAIL
            User.findOne({email: email})
            .then((result)=> {
                if(result){
                    errors.push({msg: "Email already exists"});
                    res.render("user_registration", errors, name, email, pass1, pass2)
                }else{
                    //HERE WE TRY TO ENCRYPT OUR PASSWORD
                    bcrypt.hash(pass1, 10, (error, hash)=>{
                        const nUser = new User({
                            name, email, password: hash,
                        })
                        try{
                            nUser.save();
                            req.flash('message', "Registration Successful. You can now Signup")
                            res.redirect('/user_login');
                        }
                        catch(err){
                            req.flash('error_msg', "Could not save into the Database");
                            res.redirect('user_registration');
                        }
                    })
                }
            })
            .catch((err)=> {
                res.send("There's a problem");
                console.log(err);
            })
        }
}

It says the error occurs on line 66. It was supposed to save users into the database after inputing their details but it keeps giving me TypeError.

2

Answers


  1. Check and confirm if pass1 and pass2 are being passed as strings and not numbers.

    If they are being passed as strings, please add a console log before you check for the length and share it here, please.

    Login or Signup to reply.
  2. You can use optional chaining, like

            if(pass1?.length < 6){   //line 66
                errors.push({msg: "Passwords must be at least 6 characters"});
            }
    

    but note that in this case, if pass1 is falsy, then its length will be evaluated as undefined and the comparison will be false. If this is just what you need (to have an error for pass1 being required, but to not show its length issue when it’s not even defined), then good. If not, then you can further elaborate to (pass1?.length ?? 0) < 6.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search