'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 1:[1]

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.

Solution 2:[2]

You can try a custom validation?Like this

const userSchema = new Schema({
  phone: {
    type: String,
    validate: {
      validator: function(v) {
        return /\d{3}-\d{3}-\d{4}/.test(v);
      },
      message: props => `${props.value} is not a valid phone number!`
    },
    required: [true, 'User phone number required']
  }
});

this is the docs: https://mongoosejs.com/docs/validation.html

Solution 3:[3]

Here distributers will be array of distributerObj, similarly you can define object of any type.

const distributerObj = new Schema({
    "dis_id": {
        "type": "String"
    },
    "status": {
        "type": "String"
    }
});
const productSchema = new Schema({
    "distributers": {
        "type": [distributerObj]
    }
});

Solution 4:[4]

use ref to make a relation to the defined enum schema

const actionsEnums = new Mongoose.Schema({value: { type: String, enum:["account-deletion","account-update"]}});

const Privilege = new Mongoose.Schema(
  {
    userLevel: { type: String, required: true },
    actions: [{type: String, refs: actionsEnums}],
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tomerpacific
Solution 2 yanai edri
Solution 3 Tyler2P
Solution 4 Shehan Hasintha