Shamoon
Shamoon

Reputation: 43491

How to validate string length with Mongoose?

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.

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?

Upvotes: 14

Views: 24179

Answers (3)

vaheeds
vaheeds

Reputation: 2913

The exact string length is like:

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

Upvotes: 3

Pello X
Pello X

Reputation: 481

Much simpler with this:

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

https://mongoosejs.com/docs/schematypes.html#string-validators

Upvotes: 42

Jean-Philippe Leclerc
Jean-Philippe Leclerc

Reputation: 6805

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');

Upvotes: 10

Related Questions