如何在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'
}]
})
回答:
稍微调整一下架构设置,即可添加验证选项:
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;
}
以上是 如何在Mongoose模式中设置数组大小的限制 的全部内容, 来源链接: utcz.com/qa/412693.html