如何在Mongoose模式中设置数组大小的限制 [英] How to set limit for array size in Mongoose schema

查看:297
本文介绍了如何在Mongoose模式中设置数组大小的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我在创建Mongoose模式时是否有任何方法可以设置数组大小的限制.例如

Would you be kind to tell me is there any way to set limitation on array size while creating Mongoose schema. For example

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

推荐答案

只需对架构设置进行一些细微调整,就可以添加

With a small tweak to your schema setup you can add a validate option:

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模式中设置数组大小的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆