请告诉我,在创建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;
}

Node.js相关问答推荐

为什么我的表单数据在我的POST请求中作为应用程序/json发送,为什么它返回错误请求错误?

我的Node.js应用程序没有将Mongoose方法findByIdAndDelete作为函数进行检测

条件内的表达式

Node js 处理回调和 Promise

如何从mongoose 对象内嵌套的数组中提取数组元素?

NPM如何管理node_modules传递依赖?

为什么 nginx 不将我的 react index.html 作为后备服务

运行 cypress 测试时如何指定 .env 文件用于我的开发服务器?

将文件传递到 AWS lambdas(nodejs) + API 网关后重新上传文件

为什么要加密 CSRF 令牌?

NestJS 共享模块的问题

aws cdk 2.0 init 应用程序无法构建更漂亮的问题,这来自 jest-snapshot

通过 npm 导入 Sass

Mongodb v4.0 Transaction, MongoError: Transaction numbers are allowed on a replica set member or mongos

create-react-app,安装错误(找不到命令)

遍历 NodeJS 中的一系列日期

Node.js - 使用异步库 - 带有对象的 async.foreach

如何创建安全(TLS/SSL)Websocket 服务器

如何调试 Gulp 任务?

使用 Node-sass 缩小 CSS