Best place to handle data validation with mongoose and express

express, mongoose, node.js

Solution

When using mongoose I would push most of my validation logic to the mongoose model/schema. You can use mongoose-validator which is just a wrapper around node-validator for simple model validation. If you need validation against other models or more complex logic in the validation you can write your own custom mongoose pre validate or post validate hook (see mongoose middleware).

An additional benefit you gain when using mongoose to validate your model is that mongoose adds an error property to your model which can be accessed via `model.errors[property]`. This property can be used for validation error messages on the web or for a service client.

When writing more/very complex software tying the validation to the model may become a problem. But I'd deal with this problem when it arises. Since JavaScript has functions as first class citizens your validation functions still can be reused even in these complex situations.

Problem

Maybe there is not a definitive answer here but I would like to know where to handle data validation when dealing with express.js and mongoose. Which of the following is the best practice (I currently use a combination and it's starting to feel very clumsy): - the Model (mongoose) - the Controller / Route (express) Some older posts I have read are: - this; - this; - and, this; but conflicting answers just add to the confusion. Maybe it simply isn't clear cut, in which case is one a better option?

Original source