我的验证是:
LocationSchema.path('code').validate(function(code) { return code.length === 2; }, 'Location code must be 2 characters');
因为我想强制执行code
总是2个字符.
在我的架构中,我有:
var LocationSchema = new Schema({ code: { type: String, trim: true, uppercase: true, required: true, },
我收到一个错误:Uncaught TypeError: Cannot read property 'length' of undefined
但是当我的代码运行时.有什么想法吗?
更简单:
var LocationSchema = new Schema({ code: { type: String, trim: true, uppercase: true, required: true, maxlength: 2 },
http://mongoosejs.com/docs/api.html#schema_string_SchemaString-maxlength
即使字段"代码"未定义,它也会被验证,因此您必须检查它是否具有值:
LocationSchema.path('code').validate(function(code) { return code && code.length === 2; }, 'Location code must be 2 characters');