OMGPOP OMGPOP - 1 year ago 145
Node.js Question

mongoose difference between pre save and validate? When to use which one?

Currently I am using

to do validation:

UserSchema.pre('save', true, function(next, done) {
var self = this //in case inside a callback
var msg = helper.validation.user.username(self.username)
if (msg) {
self.invalidate('username', msg)

The helper module has a function that accepts an input and returns error message.

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

There is another api
to do similar things. What's the difference between them and which one should I use in what cases?

Answer Source

Yeah, there is a small difference i know.

Pre hooks are executed before validations.

There is a closed issue on github asking for validation before pre hooks, .

And also there is a reason for not having validation before pre hooks, stated in the same link by @kamholz:

Say you have two fields, foo and fooSort, both required. fooSort is a lowercased or otherwise transformed version of foo to be used in sorting. Since fooSort can be automatically generated, it makes sense to do so in a pre-save hook. But since validation runs first, it will fail before the pre-save hook runs and has a chance to fill in the fooSort value. It isn't a question of being able to run validation again manually.

Again, if you want to validate something and then need the hook for post validate:'validate', function(next){
    console.log("post validate called");

So for summary, the one difference i see is ,

  1. u can use both as long as you get inputs to save in db directly without altering anything(only validation).

  2. If you are altering anything you have to use pre save hook.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download