Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created August 27, 2012 19:32
Show Gist options
  • Save aheckmann/3491599 to your computer and use it in GitHub Desktop.
Save aheckmann/3491599 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var assert = require('assert')
console.log('\n===========');
console.log(' mongoose version: %s', mongoose.version);
console.log('========\n\n');
var schema = new Schema({
name: String
});
schema.path('name').set(function (v) {
v = ('string' == typeof v && v || '').trim();
// manual invalidation
if (6 >= v.length)
return this.invalidate('name', 'invalid length');
return hash(v);
});
function hash (v) {
return 'hashed ' + v
}
var A = mongoose.model('A', schema);
a = new A({ name: 'woot' });
a.validate(function (err) {
console.log(err); // .. 'Validator "invalid length" failed for path name
console.log(a);
a = new A;
a.name = 'long enough'
a.validate(function (err) {
console.log(err); // undefined
console.log(a);
});
});
@geoffreyvanwyk
Copy link

If you add a 'required' SchemaType to the name path, then if the validation fails, it does so because the 'required' validator is not satisfied, but not because of the 'invalid length' validator.

@andrewjmead
Copy link

I'm seeing the same as @systemovich. this.invalidate is being taken over by required error message.

@gfaceless
Copy link

@systemovich @andrejmead
so anyway to solve the required conflict?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment