I'm using Node + Express + Mongo, my user Schema has three required fields:

  1. username
  2. email
  3. password

I already took care of how the password is handled, but when it comes to username and email, here's what I did:

router.post('/', function(req, res, next) {
  var username = req.body.username,
      password = req.body.password,
      email = req.body.email;

  User.findOne({username: username}, function(err, user) {
    if (err) { return next(err); }

    if (user) {
      req.flash('error', 'This username is already in use.');
      return res.redirect('/signup');
    }

    User.findOne({email: email}, function(err, user) {
      if (err) { return next(err); }

      if (user) {
        req.flash('error', 'This email is already in use.');
        return res.redirect('/signup');
      }

      var newUser = new User({
        username: username,
        email: email,
        password: password
      });

      newUser.save(next);
    })
  });
});

What I mean by "...display specific error messages" in the title is to be able to send an error message about the email and an error message about the username if any of them is already taken. As you can see above.

I'm calling User.findOne twice so I can check for the availability of the username and then the email. As I said, usernames and emails are unique fields. This works fine, but I'm wondering if there is a better way to achieve this. I feel like I'm doing too much.

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.