I have an schema like this:
var testSchema = new Schema({
foo: { type: String, required: true, trim: true },
bar: {
fooBar: { type: String },
barFoo: { type: String }
}
});
And I must validate values of bar
based on foo
values, something like this:
testSchema.path("bar").validate(function(bar){
if(this.foo === "someValue")
//return custom validation logic 1
else if(this.foo === "anotherString")
//return custom validation logic 2
else
return false;
});
But when I try to strat my app I get the following error:
/Users/Renato/github/local/prv/domain/models/testModel.js:34
testSchema.path("bar").validate(function(bar){
^
TypeError: Cannot call method 'validate' of undefined
What am I doing wrong here? Whats the correct way to validate this object??? I googled for it but I could not seem to find anything out! Even updated my mongoose version to ~3.5.5
Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max validators.
Mongoose gives us a set of useful built-in validation rules such: Required validator checks if a property is not empty. Numbers have min and max validators. Strings have enum , match , minlength , and maxlength validators.
If the validationLevel is strict (the default), MongoDB applies validation rules to all inserts and updates. If the validationLevel is moderate , MongoDB applies validation rules to inserts and to updates to existing documents that already fulfill the validation criteria.
No, an ObjectId field that's defined in your schema as a reference to another collection is not checked as existing in the referenced collection on a save.
Mongoose doesn't appear to consider 'bar'
to be a path
itself, but rather just a prefix
for 2 separate paths -- 'bar.fooBar'
and 'bar.barFoo'
:
testSchema.path("bar.fooBar").validate(function(fooBar){
if(this.foo === "someValue")
//return custom validation logic 1
else
return false;
});
testSchema.path("bar.barFoo").validate(function(barFoo){
if(this.foo === "anotherString")
//return custom validation logic 2
else
return false;
});
You may also find schema.pre()
to be useful for validating the model collectively (another example can be found in the Sub Docs documentation):
testSchema.pre('save', function (next) {
if(this.foo === "someValue")
return next(new Error('Invalid 1'));
else if(this.foo === "anotherString")
return next(new Error('Invalid 2'));
else
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With