为什么我不能用mongoose来validationembedded式文档? 什么是正确的方法来做到这一点?
我有这样的架构:
var testSchema = new Schema({ foo: { type: String, required: true, trim: true }, bar: { fooBar: { type: String }, barFoo: { type: String } } });
我必须根据foo
值validationbar
的值,如下所示:
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; });
但是当我尝试打我的应用程序,我得到以下错误:
/Users/Renato/github/local/prv/domain/models/testModel.js:34 testSchema.path("bar").validate(function(bar){ ^ TypeError: Cannot call method 'validate' of undefined
我在这里做错了什么? 什么是validation这个对象的正确方法? 我GOOGLE了,但我似乎无法find任何东西! 甚至更新我的mongoose版本~3.5.5
Mongoose 似乎并不认为 'bar'
本身就是一个path
,而只是一个prefix
为2个独立的path – 'bar.fooBar'
和'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; });
您还可以发现schema.pre()
对于validation模型是有用的(另一个示例可以在Sub Docs文档中find):
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(); });