node.js - mongoose difference between pre save and validate? When to use which one? -


currently using pre('save') validation:

userschema.pre('save', true, function(next, done) {     var self = //in case inside callback     var msg = helper.validation.user.username(self.username)     if (msg) {         self.invalidate('username', msg)         done(helper.getvalidationerror(msg))     }     else         done()     next() }) 

the helper module has function accepts input , returns error message.

exports.user = {     username: function(input) {         if (!input)             return 'username required'         var min = 3         var max = 10         if (input.length < min)             return 'username min of length ' + min         if (input.length > max)             return 'username max of length ' + max         return null     } } 

there api validate similar things. what's difference between them , 1 should use in cases?

update:

the validation performed before user defined hooks. can follow this github post, contributor states,

not implementing this. validating first gives chance stop before continuing user defined hooks may include async updates other collections.

if need validation run again after make change inside hook can manually run this.validate(next).


outdated:

yeah, there small difference know.

pre hooks executed before validations.

there closed issue on github asking validation before pre hooks, https://github.com/automattic/mongoose/issues/400.


, there reason not having validation before pre hooks, stated in same link @kamholz:

say have 2 fields, foo , foosort, both required. foosort lowercased or otherwise transformed version of foo used in sorting. since foosort can automatically generated, makes sense in pre-save hook. since validation runs first, fail before pre-save hook runs , has chance fill in foosort value. isn't question of being able run validation again manually.

again, if want validate , need hook post validate:

userschema.post('validate', function(next){     console.log("post validate called");     next(); }); 


summary, 1 difference see is,

  1. you can use both long inputs save in db directly without altering (only validation).

  2. if altering have use pre save hook.


Comments