4

Example I have this schema.

{
  field1: {
    type: String,
    trim: true
  },
  field2: [{
    subField1: {
      type: String,
    },
    subField2: {
      type: Number,
      default: 0
    }
  }]
}

How should I set the default value on the schema for the field2 if I just provided the field1 on the document insert?

example If i just insert {field1: "sample string data"}, then the value on the field2 is an empty array.

zer09
  • 1,507
  • 2
  • 28
  • 48

1 Answers1

5

can you try this?, use type to specify the schema and default for default values

const TesterSchema = new Schema({  
      field1: {
        type: String,
        trim: true
      },
      field2: {
        type : [{
          subField1: {
            type: String                  
          },
          subField2: {
            type: Number                  
          }
      }],
      default :[{subField2 : '0'}]
    }
  }
);

example

Tester.create({field1 : 'testing'}, function(err,doc){
    if(err) console.log(err)
    console.log(doc)
})

console output

Mongoose: testerzz.insert({ field1: 'testing', _id: ObjectId("5a6ae40a351d4254c6e0fdc2"), field2: [ { subField2: 0, _id: ObjectId("5a6ae40a351d4254c6e0fdc1") } ], __v: 0 })
{ __v: 0,
  field1: 'testing',
  _id: 5a6ae40a351d4254c6e0fdc2,
  field2: [ { subField2: 0, _id: 5a6ae40a351d4254c6e0fdc1 } ] }

mongo CLI

> db.testerzz.find({_id: ObjectId("5a6ae40a351d4254c6e0fdc2")}).pretty()
{
    "_id" : ObjectId("5a6ae40a351d4254c6e0fdc2"),
    "field1" : "testing",
    "field2" : [
        {
            "subField2" : 0,
            "_id" : ObjectId("5a6ae40a351d4254c6e0fdc1")
        }
    ],
    "__v" : 0
}
> 
Saravana
  • 12,647
  • 2
  • 39
  • 57