我的验证是:
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
但是当我的代码运行时。有什么想法吗?
答案 0 :(得分:21)
更简单:
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
答案 1 :(得分:7)
字段"代码"即使它未定义也会被验证,因此您必须检查它是否具有值:
LocationSchema.path('code').validate(function(code) {
return code && code.length === 2;
}, 'Location code must be 2 characters');
答案 2 :(得分:1)
确切字符串长度如下:
...
minlength: 2,
maxlength: 2,
...