猫鼬模式:如何设置数组中的最大项目数?

时间:2020-04-12 17:45:05

标签: node.js mongodb express mongoose

我有一个猫鼬模式,其中包含一个对象数组和一个字符串数组。在这两种情况下,如何设置验证器以将可插入的项目数限制为10?

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

1 个答案:

答案 0 :(得分:1)

数组没有默认的maxlength选项。

解决方法1:您可以通过以下方式定义custom validator

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
}]

解决方法2:您可以通过以下方式定义pre hook

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