How to set limit for array size in Mongoose schema

With a small tweak to your schema setup you can add a validate option:

var peopleSchema = new Schema({
  name: {
    type: String,
    required: true,
    default: true
  },
  friends: {
    type: [{
      type: Schema.Types.ObjectId,
      ref: 'peopleModel'
    }],
    validate: [arrayLimit, '{PATH} exceeds the limit of 10']
  }
});

function arrayLimit(val) {
  return val.length <= 10;
}

Leave a Comment