MazMat
MazMat

Reputation: 2094

Setting default value for nested object in array in mongoose schema

I want to achieve an element in schema like that:

array: [
    {id: 0},
    {id: 1},
    {id: 2}
]

In othr words, I want to declare an array that will hold 3 objects and those 3 objects should already have ids set. I had several attempts, but the objects never showed up

Upvotes: 1

Views: 1457

Answers (1)

Akrion
Akrion

Reputation: 18515

There is not a lot of detail to your question so I am not sure what those ids are/should be but you could do this in your schema:

var YourSchema = new Schema({
  foo: {
    type: [{}],
    default: [{id: 1}, {id:2}, {id:3}]
  }
}

That would on record creation setup that array with those objects inside.

The result would be:

{
  "_id" : ObjectId("SOMEID"),
  "foo" : [ 
      {
          "id" : 1
      }, 
      {
          "id" : 2
      }, 
      {
          "id" : 3
      }
  ],
}

Upvotes: 3

Related Questions