Let's say I have a very simple schema with a custom validation function that always returns false.
var MofoSchema = new mongoose.Schema({
name: String
});
MofoSchema.path('name').validate(function (value) {
console.log("I'm validating");
return false;
}, 'No pasaran');
mongoose.model('Mofo', MofoSchema);
Then I create a new instance of my document and I validate it:
var Mofo = mongoose.model('Mofo');
var mofo = new Mofo({name: "Tarte flambée"});
mofo.validate(function(err) {
console.log(err);
});
Perfect, the custom validator function is called and err is filled.
But now I do the same with no data:
var Mofo = mongoose.model('Mofo');
var mofo = new Mofo({});
mofo.validate(function(err) {
console.log(err);
});
The custom validator function is not called and err is undefined.
Why? I don't understand why Mongoose is not running the custom validator.
Is this behaviour by design? Is it a bug? Should I hack a turnaround? Should I check manually for empty data before validation?
Am I doing something wrong?
PS: If you call save, the document will be saved as empty in MongoDB despite of the custom validator.