Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

node.js - How to set limit for array size in Mongoose schema

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'
    }]
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...