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

Ign*_*kin 28 mongoose mongodb node.js

您是否善意告诉我在创建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'
    }]
})
Run Code Online (Sandbox Code Playgroud)

Jas*_*ust 71

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

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;
}
Run Code Online (Sandbox Code Playgroud)


Sar*_*ana 8

从 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"
            }
         }
      }
   }
});
Run Code Online (Sandbox Code Playgroud)

收藏

> db.people.find()
Run Code Online (Sandbox Code Playgroud)

有效证件

> db.people.insert({name: 'abc' , friends : ['1','2','3','4','5','6','7','8','9','10']})
WriteResult({ "nInserted" : 1 })
Run Code Online (Sandbox Code Playgroud)

无效文件

> 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"
    }
})
Run Code Online (Sandbox Code Playgroud)

> db.people.find()
{ "_id" : ObjectId("5a9779b60546616d5377ec1c"), "name" : "abc", "friends" : [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ] }
> 
Run Code Online (Sandbox Code Playgroud)


Lui*_*is 8

您可以在将新朋友 ID 推送到数组时使用 $slice 修饰符 https://docs.mongodb.com/manual/reference/operator/update/slice/#up._S_slice

$push: {
  friends: {
   $each: [id],
   $slice: -10
  }
}
Run Code Online (Sandbox Code Playgroud)