title: How does one apply field type validation in Mongoose.js without getting a CastError?
body: <p>I'm attempting to use Express and Mongoose to create a simple form which allows the user to add new items to a collection. </p>
  
  <p>Mongoose schema:</p>
  
  <pre><code>var Item = new Schema({
    name   : {type : String, required : true},
    price  : {type : Number, required : true},
    description : {type: String, required: true},
  });
  </code></pre>
  
  <p>Express route:</p>
  
  <pre><code>var create = function(req, res) {
    Item.create(req.body, function(err) {
      if (err) return res.render('admin/items/new', {title: "New Item", errors: _.values(err.errors)});
      res.redirect('/admin/items/index');
    });
  };
  </code></pre>
  
  <p>Simple enough so far. What I want to do is add appropriate validation to ensure the <code>price</code> entered by the user is numeric and if not show an appropriate error. </p>
  
  <p>With the code above, if the user types non-numeric characters into the price text field I get a CastError thrown. </p>
  
  <p>So, I have tried adding the following validation to my schema:</p>
  
  <pre><code>Item.path('price').validate(function(v, fn) {
    if (typeof v === 'number' || v === undefined) return fn(true);
    return fn(false);
  }, "must-be-numeric");
  </code></pre>
  
  <p>However, it seems that Mongoose attempts to cast the value before applying this validation, so it is not possible to return an appropriate validation error for this, you still just get a CastError. Moreover the CastError prevents any validation checks on other fields being run. </p>
  
  <p>I would think that what I'm trying to do is fairly common (in Rails you'd just add <code>validate :price, :numericality =&gt; true</code> to your model and that would be it). </p>
  
  <p><strong>Is there an obvious pattern I'm missing which facilitates this sort of type validation?</strong></p>
  
  <p><strong>How does everyone else do this?</strong></p>
  
  <hr>
  
  <p>Things I've tried/thought of:</p>
  
  <ul>
  <li>I realise I could use a secondary validation library such as node-validator to "pre-validate" the form fields before passing them to Mongoose. However, I don't really want the code duplication, or the boilerplate mess of combining error objects from two validators to give a single set of errors which will be fed back to the user.</li>
  <li>Ideally I'd use the HTML5 "number" <code>input</code> element to prevent erroneous user input, but given Firefox and IE don't support it yet it's a non-starter. </li>
  </ul>