mongoose validate array of references required 1

mongoose validate array of references required

const questionSchema = new mongoose.Schema({
  question: {
      type: String,
      required: [true, 'Question Required'],
      trim: true
  },
  options: {
    type: [{
        optionNo: Number,
        optionValue:{
            type: String,
            required: [true,'Option required'],
            trim: true
        }
    }],
    validate: [(val) -> val.length > 1, 'Must have minimum two options']
  }
});

Here is what the above code is Doing:
1. We are creating a new schema for our question model.
2. We are defining the question field as a string and making it required.
3. We are defining the options field as an array of objects.
4. We are defining the optionNo field as a number.
5. We are defining the optionValue field as a string and making it required.
6. We are validating the options field to make sure that it has at least two options.

Similar Posts