Search code examples
node.jsarraysmongodbmongooseenums

Mongoose - array of enum strings


I have a Schema that has a property with the type of array of strings that are predefined.

This is what I've tried to do:

interests: {
    type: [String],
    enum: ['football', 'basketball', 'read'],
    required: true
}

The thing is that when I'm trying to enter a wrong value that isn't defined on the enum, to the array it wouldn't validate it with the enum list.

for example, this would pass which it shouldn't:

{ "interests": ["football", "asdf"] }

because "asdf" isn't predefined in the enum list it shouldn't pass the validation but unfortunately, it passes the validation and saves it.

I've tried to check this thing with a string type of values instead of an array of strings and it works.

for example:

interests: {
    type: String,
    enum: ['football', 'basketball', 'read'],
    required: true
}

for example, this is failing as expected:

{ "interest": "asdf" }

In conclusion, I need a schema's property with a type of array of strings that would check it's elements based on predefined values

Is the most effective way to achieve this goal is by using the validate method or there is a better way?


Solution

  • Quoting from here:

    const SubStrSz = new mongoose.Schema({ value: { type: String, enum: ['qwerty', 'asdf'] } });
    const MySchema = new mongoose.Schema({ array: [SubStrSz] });
    

    Using that technique you will able to validate values inside of your array.