如何用Mongoose验证字符串长度?

时间:2014-03-14 13:10:28

标签: node.js mongodb mongoose

我的验证是:

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但是当我的代码运行时。有什么想法吗?

3 个答案:

答案 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,
...
相关问题