Let's suppose I have an Express model:
var SchemaDescription = {};
var Model = = new mongoose.Schema(SchemaDescription);
Express allows to tune up data validation in SchemaDescription. On save it works perfectly, but on update, because of mongoose nature, it isn't called, and there is no clean way to call it.
I tried Model.pre('update', ...);
but didn't found the way to access/correct model's data before writing to the DB: because complex validation logics, which, for example, re-formats some data before checking.
A logical solution is to put validation code to save/update controller's handlers, but it leads to duplication of the code. To keep MVC pattern as for save, as for update, I'd like to put a public method to the model, or the schema, which gets input data and validate them.
My attempts look like:
Model.prototype.validate = function(input, isUpdate) {...};
or
SchemaDescription.validate = function(...) {...};
in different combinations.
The response always looks like "Cannot set property 'validate' of undefined"
- Is there an approach to put a custom public function-member to an Express model/schema for being called in controllers?
- What approach may be used to validate data on save and update, without code duplication, or/and putting validation logics to controllers?