How to validate an array of string with an enum in Mongoose?

Viewed 382

I have an array of strings, that can only contain 6 kind of values. I've written this validation in my Mongoose schema:

skills: [
      { type: String, enum: ["marketing", "sales", "tech", "hr", "management", "finance"] },
    ]

When creating an user with the key skills: ["sales", "hr"], mongoose crashes, claiming that:

Error: UserDB validation failed: skills.0: ["sales", "hr"] is not a valid enum value for path skills.0.

How to fix this?

1 Answers

There is a issue already fixed in mongoose issues-6102, and provided a solution here,

skills: {
  type: [
    { 
      type: String, 
      enum: ["marketing", "sales", "tech", "hr", "management", "finance"] 
    }
  ]
}
Related