Search code examples
mongodbmongoosemongoose-schema

Mongoose specify optional array of objects


One of the keys in my mongo collection is

    options: [
      new mongoose.Schema(
        {
          answer: {
            type: String,
            required: true,
          },
          value: {
            type: Number,
            min: -10,
            max: 10,
            required: true,
          },
        },
        { _id: false }
      ),
    ],

The issue I'm having here is that options is optional but when there's no options field filled out, the inserted document has options: []

I believe I'm able to solve this normally by putting a default: undefined but I'm not sure how to go about doing this for this array of objects.

Thanks!


Solution

  • In mongoose an empty array is a default value for an array type. You can override it by using default field this way:

    let optionsSchema = new mongoose.Schema(
        {
            answer: {
                type: String,
                required: true,
            },
            value: {
                type: Number,
                min: -10,
                max: 10,
                required: true,
            },
        },
        { _id: false });
    
    
    const RootSchema = new Schema({
        options : {
            type: [optionsSchema],
            default: undefined
        }
    })