【问题标题】:Mongoose schema: how to set max number of items in an array?Mongoose 模式:如何设置数组中的最大项目数?
【发布时间】:2020-07-25 06:59:56
【问题描述】:

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

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

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案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();
    });
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2020-06-24
      • 2020-04-22
      • 2019-07-30
      • 2015-01-09
      • 1970-01-01
      • 2013-01-25
      • 2016-05-27
      • 1970-01-01
      相关资源
      最近更新 更多