Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Array field with default array containing values

The Mongoose docs suggest overriding the default value of [] for an array field like this:

new Schema({
  toys: {
    type: [ToySchema],
    default: undefined
  }
});

I'd like to have an array of strings, with an enum and with a default value if none is supplied.

Thus, every document has type 'foo' if none is specified, but documents may be 'foo' and 'bar'.

Is that possible?

like image 318
LondonRob Avatar asked Jan 28 '23 01:01

LondonRob


1 Answers

Although the docs don't mention it, a default value can be given, in the way you'd expect.

You can have an enum array with a default value like this:

new Schema({
  toys: {
    type:[{ type: String, enum: ['foo', 'bar', 'baz'] }],
    default: ['foo']
  }
});
like image 126
LondonRob Avatar answered Feb 12 '23 09:02

LondonRob