如何在Mongoose模式中设置数组大小限制

你会友好地告诉我有什么方法可以在创buildMongoose模式时设置数组大小的限制。 例如

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' }] }) 

通过对模式设置的小调整,您可以添加一个validation选项:

 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; }