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

时间:2021-12-25 18:39:09

My validation is:

我的验证是:

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

as I want to enforce that the code is always 2 characters.

因为我想强制执行代码总是2个字符。

In my schema, I have:

在我的架构中,我有:

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

I'm getting an error: Uncaught TypeError: Cannot read property 'length' of undefined however when my code runs. Any thoughts?

我收到一个错误:未捕获TypeError:无法读取未定义的属性'length'但是当我的代码运行时。有什么想法吗?

2 个解决方案

#1


7  

The field "code" is validated even if it is undefined so you must check if it has a value:

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

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

#2


15  

Much simpler with this:

更简单:

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  

The field "code" is validated even if it is undefined so you must check if it has a value:

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

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

#2


15  

Much simpler with this:

更简单:

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