title: How to check if user with email already exists?
body: <p>I'm trying to prevent registration with a previously registered email. I tried to create a custom validation in mongoose schema. but it gave me an error <em>ValidationError: User validation failed
      at MongooseError.ValidationError</em>. The code is down bellow. Can some one tell me where is the error or a better way to check if the user email exists in db. </p>
  
  <pre><code>// user schema 
  var UserSchema = mongoose.Schema({
      username: {
          type: String,
          index: true,
          require: true
      },
      password: {
          type: String,
          require: true
      },
      email: {
          type: String,
          lowercase: true,
          trim: true,
          index: {
              unique: true,
          },
          validate: {
              validator : isEmailExists, msg: 'Email already exists'
          }
      },
      name: {
          type: String
      },
      admin: Boolean,
      active: Boolean,
  });
  
  // validation
  function isEmailExists(email, callback) {
      if (email) {
          mongoose.models['User'].count({ _id: { '$ne': this._id }, email: email }, function (err, result) {
              if (err) {
                  return callback(err);
              }
              callback(!result);
          })
      }
  }
  // createUser function
  module.exports.createUser = function(newUser, callback){
      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(newUser.password, salt, function(err, hash) {
              newUser.password = hash;
              newUser.save(callback);
          });
      });
  }
  </code></pre>
  
  <p><strong>Router</strong></p>
  
  <pre><code>router.post('/register', function(req, res, next) {
      var name = req.body.name;
      var email = req.body.email;
      var password = req.body.password;
      var confirmedPassword = req.body.confirmedPassword;
  
      // Validation
      req.checkBody('name', 'Name is required').notEmpty();
      req.checkBody('email', 'Email is required').notEmpty();
      req.checkBody('email', 'Email is not valid').isEmail();
      req.checkBody('password', 'Password is required').notEmpty();
      req.checkBody('confirmedPassword', 'Passwords do not match').equals(req.body.password);
  
      var errors = req.validationErrors();
  
      if (errors) {
          res.render('register', {
              errors: errors
          });
      } else {
          var newUser = new User({
              name: name,
              email: email,
              password: password,
              admin: false,
              active: false
          });
  
          User.createUser(newUser, function (err, user) {
              if (err) {
                  throw err;
              }
          });
  
          req.flash('success_msg', 'You are registerd and can now login');
          res.redirect('/users/login');
      }
  </code></pre>