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

Sha*_*oon 7 mongoose mongodb node.js

我的验证是:

LocationSchema.path('code').validate(function(code) {
  return code.length === 2;
}, 'Location code must be 2 characters');
Run Code Online (Sandbox Code Playgroud)

因为我想强制执行code总是2个字符.

在我的架构中,我有:

var LocationSchema = new Schema({
  code: {
    type: String,
    trim: true,
    uppercase: true,
    required: true,
  },
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:Uncaught TypeError: Cannot read property 'length' of undefined但是当我的代码运行时.有什么想法吗?

小智 24

更简单:

var LocationSchema = new Schema({
  code: {
    type: String,
    trim: true,
    uppercase: true,
    required: true,
    maxlength: 2
  },
Run Code Online (Sandbox Code Playgroud)

http://mongoosejs.com/docs/api.html#schema_string_SchemaString-maxlength


Jea*_*erc 8

即使字段"代码"未定义,它也会被验证,因此您必须检查它是否具有值:

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