title: Form validation using mongoose
body: <p><strong>My use case:</strong></p>
  
  <p>I am working on a <strong>signup page</strong> and I am sending an ajax request for the username to my server. The server should check if it is line with the validation rules (alphanumeric for example) and if the username is forgiven or free to use.</p>
  
  <p><strong>My idea:</strong></p>
  
  <p>I have defined validation rules on my mongoose model which. In order to avoid defining the exact same validation rules twice I wanted to use the mongoose schema to check against the validation rules and if the query passes then it should try to find the username in the db to check if it's still free.</p>
  
  <p><strong>The problem:</strong></p>
  
  <p>Unfortunately it seems like it doesn't check the validation for queries (instead it only does so before saving), hence I don't know how I could use the mongoose validation rules to validate the username input too.</p>
  
  <p><strong>My code:</strong></p>
  
  <p><strong>checkSignUp:</strong></p>
  
  <pre><code>function checkSignup(req, res, next) {
      var formField = req.params.field
      var expectedFormFields = ["username", "emailAddress", "password"]
  
      // Check if it's an expected field
      if(!expectedFormFields.includes(formField))
          res.status(403).send('Invalid request')
  
      if(formField == 'username') {
          var user = User.findOne({'local.username': req.body.value}, function (err, user) {
              if(err)
                  res.status(403).send('Invalid request')
  
              if(user)
                  res.status(409).send('Username is already forgiven')
  
              res.status(200).send()
          })
      }
  
      res.status(409).send('Unknown validation check, please contact a staff member')
  }
  </code></pre>
  
  <p><strong>My mongoose schema:</strong></p>
  
  <pre><code>var userSchema = mongoose.Schema({
      local: {
          username: {
              type: String,
              required: [true, 'Empty usernames are not allowed'],
              validate: usernameValidator
          }});
  </code></pre>
  
  <p><strong>The username validator:</strong></p>
  
  <pre><code>var usernameValidator = [
      validate({
          validator: 'isLength',
          arguments: [3, 50],
          message: 'Userame should be between {ARGS[0]} and {ARGS[1]} characters'
      }),
      validate({
          validator: 'isAlphanumeric',
          passIfEmpty: false,
          message: 'Name should contain alpha-numeric characters only'
      })
  ]
  </code></pre>