gpt4 book ai didi

node.js - Mongoose 模式 : how to set max number of items in an array?

转载 作者:行者123 更新时间:2023-12-02 19:35:05 25 4
gpt4 key购买 nike

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

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

最佳答案

数组没有默认的 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();
});

关于node.js - Mongoose 模式 : how to set max number of items in an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61175684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com