3
votes

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.

2

2 Answers

3
votes

I think mongoose will only validate for existing field.

So you can use 'null' value to activate validation

var mofo = new Mofo({name: null});

For empty or undefined

var MofoSchema = new mongoose.Schema({
  name: {type: String, required: true}
});

MofoSchema.path('name').validate(function (value) {...}, 'no pasaran');
0
votes

You can do:

var mofo = new Mofo({ name: { type: String, default: ''} });

This will ensure you always have a value on that key to trigger validation. It also makes your schema definition easier to read.