I have an api rest resource that accepts a JSON message. Example:
{ "location": { "coordinates": [ -122.41941550000001, 37.7749295 ] }
Coordinates are then collected from an Express request:
module.exports.create = function(req, res, next) { var coordinates = req.body.location.coordinates; ....
They are then passed to the Mongoose model. I am writing tests against this where location.coordinates coordinates are missing, for example.
{ "foo": { "bar": [ -122.41941550000001, 37.7749295 ] }
Then this is not done in the model validation section:
locationSchema.path('location.coordinates').validate(function(coordinates){ ^ TypeError: Cannot call method 'validate' of undefined
So my question is, how can I verify that the input is correct? Should this be done on the route before getting into the model, or should it be done in the model? Any examples of how one might appreciate.
For reference, the Mongoose model looks something like this:
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.');