How to check string length using Mongoose?

My check:

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

since I want to ensure that codethere are always 2 characters.

In my scheme, I have:

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

I get an error: Uncaught TypeError: Cannot read property 'length' of undefinedhowever, when my code works. Any thoughts?

+6
source share
2 answers

The code field is checked even if it is undefined, so you should check if it has a value:

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

Much easier 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

+21
source

Source: https://habr.com/ru/post/1531767/


All Articles