Node.js 如何使用Mongoose验证字符串长度?

Node.js 如何使用Mongoose验证字符串长度?,node.js,mongodb,mongoose,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, upper

我的确认是:

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,
  },
我收到一个错误:
uncaughttypeerror:无法读取未定义的属性“length”
,但是当我的代码运行时。有什么想法吗?

即使“代码”字段未定义,也会进行验证,因此您必须检查它是否有值:

LocationSchema.path('code').validate(function(code) {
  return code && code.length === 2;
}, 'Location code must be 2 characters');

更简单的是:

var LocationSchema = new Schema({
  code: {
    type: String,
    trim: true,
    uppercase: true,
    required: true,
    maxlength: 2
  },

准确的字符串长度如下所示:

...
minlength: 2,
maxlength: 2,
...