我有这样的架构:
var testSchema = new Schema({ foo: { type: String,required: true,trim: true },bar: { fooBar: { type: String },barFoo: { type: String } } });
我必须根据foo值验证bar的值,如下所示:
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; });
但当我尝试strat我的应用程序时,我收到以下错误:
/Users/Renato/github/local/prv/domain/models/testModel.js:34 testSchema.path("bar").validate(function(bar){ ^ TypeError: Cannot call method 'validate' of undefined
我在这做错了什么?什么是验证这个对象的正确方法???我用Google搜索,但我似乎找不到任何东西!甚至将我的猫鼬版本更新为~3.5.5
解决方法
Mongoose
doesn’t appear to consider‘bar’本身就是一条路径,而只是两条独立路径的前缀 – ‘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()
用于集体验证模型(另一个示例可以在Sub Docs文档中找到):
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(); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。