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

时间:2015-02-14 10:45:37

标签: node.js mongodb 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'
    }]
})

4 个答案:

答案 0 :(得分:65)

通过对架构设置进行小幅调整,您可以添加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;
}

答案 1 :(得分:3)

从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"
            }
         }
      }
   }
});

集合

> db.people.find()

有效文件

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

文件无效

> 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"
    }
})

查找

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

答案 2 :(得分:1)

这是我通过外部函数分配给ToId的架构和数组的限制。

const mongoose = require("mongoose");
    const Schema = mongoose.Schema;

const taskSchema = new Schema({
  parentTask: {
    trim: true,
    type: Schema.Types.ObjectId,
    ref: "task",
  },
  assignedToId: [{
    trim: true,
    type: Schema.Types.ObjectId,
    ref: "Employees",
  }],
  createdBy: {
    trim: true,
    type: Schema.Types.ObjectId,
    ref: "Employees",
    required: [true, "User ID is required"]
  },
  createdByName: {
    trim: true,
    type: String,
    required: [true, "Creater name is required"]
  },
},
  {
    timestamps: true
  });

// Validations for assignedTo employees' size
taskSchema.path('assignedToId').validate(function (value) {
  console.log(value.length)
  if (value.length > 10) {
    throw new Error("Assigned person's size can't be greater than 10!");
  }
});

const Tasks = mongoose.model("Tasks", taskSchema);

module.exports = Tasks;

答案 3 :(得分:0)

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

$push: {
  friends: {
   $each: [id],
   $slice: -10
  }
}