Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo User Registration Adding Data to the Database

Martin Coutts
Martin Coutts
18,154 Points

Getting all fields required error handler even when it is my two passwords not being the same causing the error

Here's my code so far, from what I can see it is ok but might be missing something obvious

router.post('/register', function(req, res, next){ if( req.body.email && req.body.name && req.body.favouriteBook && req.body.password && req.body.confirmPassword){

    // confirm that user typed same password twice
    if(req.body.password !== req.body.confirmPassword){
        var err = new Error('Passwords do not match.');
        err.status = 400;
        return next(err);
    }
} else {
    var err = new Error('All fields required.');
    err.status = 400;
    return next(err);
}

})

1 Answer

Shehan Dissanayake
Shehan Dissanayake
19,119 Points
// POST /register
router.post('/register', function(req, res, next) {
  if(
    req.body.name &&
    req.body.email &&
    req.body.favoriteBook &&
    req.body.password &&
    req.body.confirmPassword
  ){
    //password match check
    if(req.body.password !== req.body.confirmPassword){
      const err = new Error('Passwords Do Not Match');
      err.status = 400;
      return next(err);
    }
    //creating the object that we are going to insert into mongo
    const userData = {
      name : req.body.name,
      email : req.body.email,
      favoriteBook : req.body.favoriteBook,
      password : req.body.password
    };

    user.create(userData,function(error,user){
      if(error){
        return next(error);
      }else{
        req.session.userId = user._id;
        return res.redirect('/profile');
      }
    });


  }else{
    const err = new Error('All fields required');
    err.status = 400;
    return next(err);
  }
});

Try This

Martin Coutts
Martin Coutts
18,154 Points

Thanks man, seems to have fixed the issue. Think I missed brackets on the if password statement now that I look at it