Don*_*al0 2 mongoose mongodb node.js express
我有一个猫鼬模式,其中包含一个对象数组和一个字符串数组。在这两种情况下,如何设置验证器以将可以插入的项目数量限制为 10 个?
todoList: [{ type: String }],
pictures: [{ type: String }],Run Code Online (Sandbox Code Playgroud)
maxlength数组没有默认选项。
解决方法 1:您可以通过以下方式定义自定义验证器:
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
}]
Run Code Online (Sandbox Code Playgroud)
解决方法 2:您可以这样定义pre hook :
schema.pre('validate', function(next) {
if (this.todoList.length > 10) throw("todoList exceeds maximum array size (10)!");
next();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3612 次 |
| 最近记录: |