title: Node.js, Express, Mongoose - input validation - within route or model?
body: <p>I have a rest api resource that accepts a JSON post. Example:</p>
  
  <pre><code>{
  "location": {
      "coordinates": [
          -122.41941550000001,
          37.7749295
      ]
  }
  </code></pre>
  
  <p>The coordinates are then collected from the request by Express:</p>
  
  <pre><code>module.exports.create = function(req, res, next) {
  
      var coordinates = req.body.location.coordinates;
      ....
  </code></pre>
  
  <p>These are then submitted to a Mongoose model. I am writing tests against this where the location.coordinates is missing e.g.</p>
  
  <pre><code>{
  "foo": {
      "bar": [
          -122.41941550000001,
          37.7749295
      ]
  }
  </code></pre>
  
  <p>This then fails within the validation section of the Model with :</p>
  
  <pre><code>locationSchema.path('location.coordinates').validate(function(coordinates){
                                              ^
  TypeError: Cannot call method 'validate' of undefined
  </code></pre>
  
  <p><strong>So my question is how would I validate that the input is correct? Should this be done in the route before getting to the model, or should it be done in the model? Any examples of how would also be appreciated.</strong></p>
  
  <p>For reference the Mongoose model looks something like:</p>
  
  <pre><code>var locationSchema = new Schema({
      userid: { type: Number, required: true },
      location: {
          type: [{
              type: "String",
              required: true,
              enum: ['Point', 'LineString', 'Polygon'],
              default: 'Point'
          }], required: true,
          coordinates: { type: [Number], required:true }
      },
      create_date: { type: Date, default: Date.now }
  });
  
  
  locationSchema.path('location.coordinates').validate(function(coordinates){
      ...
  }, 'Invalid latitude or longitude.');
  </code></pre>