1

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?
anton
  • 247
  • 3
  • 13

1 Answers1

1

You don't have an Express model, you have a Mongoose model. According to the latest documentation, you can explicitly activate validation on update: http://mongoosejs.com/docs/validation.html#update-validators

Daniel Diekmeier
  • 3,401
  • 18
  • 33
  • That's a good idea, thank you. What if I have virtual password field, as was recommended here http://stackoverflow.com/a/14015331/3706373 ? In case of update (findOneAndUpdate) I cannot get this._password or this.password inside the validator to check it for emptiness, or for length. Seems it is a weak side of the approach, may it be avoided? – anton May 11 '16 at 17:18