bpii6w
Last Updated: February 25, 2016
·
112
· dsdenes
0 upscw4bodubwawudgjohwsiwd2xou7wdarmewslq9frvpiywhverfvlvfkkzfeels0zdqjbxogwk

Mongoose validate fail when using set

Take care, if you use both set and validate in your schema definition, the set will run first. If it's returning with an empty string for example, the validation will not run, and thus it cannot block the document creation.

So this is BAD, the validator will NOT run, because set returns with an empty string.

var mongoose = require('mongoose');
var schema = new mongoose.Schema({
  phone: { 
    type: String, 
    validate: function(_phone) {
        _phone = _phone.replace('+', '');
        return !!(phoneValidator(_phone, 'HUN').length);
    },
    set: function(_phone) {
      _phone = _phone.replace('+', '');
      return phoneValidator(_phone, 'HUN')[0];
    }
  }
}
Say Thanks
Respond