programing

Mongoose 스키마에서 어레이 크기에 대한 제한을 설정하는 방법

minimums 2023. 5. 23. 21:43
반응형

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

스키마 설정을 약간 조정하면 유효성 검사 옵션을 추가할 수 있습니다.

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

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

친구 ID를 어레이 https://docs.mongodb.com/manual/reference/operator/update/slice/ #up._S_slice에 푸시할 때 $filename 수식어를 사용할 수 있습니다.

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

이것은 외부 함수를 통해 할당된 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;

제가 알고 있는 가장 좋은 방법은 여러 어레이에서 함수를 재사용할 수 있도록 인수로 숫자를 전달하는 폐쇄 함수를 만드는 것입니다.

이렇게 보일 것입니다.

 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: [limitArray(10), 'Cannot have more than ten 
        friends']
    }
})

function limitArray(limit){
    return function(value){
        return value.length <= limit;
    }
}

내 프로젝트에서는 이 기능을 자체 파일에 내보내기로 포함시켜 필요한 스키마 수에 상관없이 가져올 수 있습니다.

언급URL : https://stackoverflow.com/questions/28514790/how-to-set-limit-for-array-size-in-mongoose-schema

반응형