5

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?

2
  • 1
    This second schema works fine, could you show how you save/retrieve your document ? Commented Dec 5, 2018 at 20:34
  • My bad. It does work in the way I specified. Not sure what I was doing, but I obviously wrote the question right and wrote my own code wrong! Might be useful to post this as an answer for future users who want to do this! Commented Dec 6, 2018 at 18:05

1 Answer 1

10

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']
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.