【发布时间】:2020-07-25 06:59:56
【问题描述】:
我有一个猫鼬模式,它包含一个对象数组和一个字符串数组。在这两种情况下,如何设置验证器以限制可以插入的项目数为 10?
todoList: [{ type: String }],
pictures: [{ type: String }],
【问题讨论】:
标签: node.js mongodb express mongoose
我有一个猫鼬模式,它包含一个对象数组和一个字符串数组。在这两种情况下,如何设置验证器以限制可以插入的项目数为 10?
todoList: [{ type: String }],
pictures: [{ type: String }],
【问题讨论】:
标签: node.js mongodb express mongoose
数组没有默认的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();
});
【讨论】: