Mongoose schema: how to set max number of items in an array?

Viewed 2434

I have a mongoose schema, that contains an array of objects and an array of strings. How to set validators in order to limit the number of items that can be inserted to 10 in these two cases?

    todoList: [{ type: String }],
    pictures: [{ type: String }],

1 Answers

There is no default maxlength option for arrays.

Workaround 1: You can define custom validator this way:

todoList: [{ 
    type: String,
    validate: {
      validator: function(v,x,z) {
          return !(this.todoList.length > 10);  
      }, 
      message: props => `${props.value} exceeds maximum array size (10)!`
    },
    required: true
}]

Workaround 2: You can define pre hook this way:

schema.pre('validate', function(next) {
    if (this.todoList.length > 10) throw("todoList exceeds maximum array size (10)!");
    next();
});
Related