如何在Mongoose模式中设置数组大小的限制
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Mongoose模式中设置数组大小的限制相关的知识,希望对你有一定的参考价值。
您是否善意告诉我在创建Mongoose模式时是否有任何方法可以限制数组大小。例如
var peopleSchema = new Schema({
name: {
type: String,
required: true,
default: true
},
/* here I want to have limit: no more than 10 friends.
Is it possible to define in schema?*/
friends: [{
type: Schema.Types.ObjectId,
ref: 'peopleModel'
}]
})
答案
通过对模式设置的小调整,您可以添加validate选项:
var peopleSchema = new Schema({
name: {
type: String,
required: true,
default: true
},
friends: {
type: [{
type: Schema.Types.ObjectId,
ref: 'peopleModel'
}],
validate: [arrayLimit, '{PATH} exceeds the limit of 10']
}
});
function arrayLimit(val) {
return val.length <= 10;
}
另一答案
从mongo 3.6开始,您可以在服务器端添加对集合的验证,插入/更新的每个文档将针对验证器$jsonSchema进行验证,只有有效的插入,验证错误将针对无效文档
db.createCollection("people", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name" ],
properties: {
name: {
bsonType: ["string"],
description: "must be a string"
},
friends: {
bsonType: ["array"],
items : { bsonType: ["string"] },
minItems: 0,
maxItems: 10,
description: "must be a array of string and max is 10"
}
}
}
}
});
采集
> db.people.find()
有效证件
> db.people.insert({name: 'abc' , friends : ['1','2','3','4','5','6','7','8','9','10']})
WriteResult({ "nInserted" : 1 })
文件无效
> db.people.insert({name: 'def' , friends : ['1','2','3','4','5','6','7','8','9','10', '11']})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
找
> db.people.find()
{ "_id" : ObjectId("5a9779b60546616d5377ec1c"), "name" : "abc", "friends" : [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ] }
>
以上是关于如何在Mongoose模式中设置数组大小的限制的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Office 365 环境中设置联机 Exchange 邮箱大小和限制