Home > Back-end >  mongoose - How can I set the role field with only predefined options
mongoose - How can I set the role field with only predefined options

Time:08-07

Here's my user Schema :

const userSchema = new mongoose.Schema({
  username: {
      type: String,
      validate: function (v) {
          return /([0-9a-zA-Z])\w{6,}/.test(v);
      },
      required: [true, "Username required"],
  },
  passwordHash: {
      type: String,
      required: [true, "PasswordHash required"],
  },
  role: {
      type: String,
      required: [true, "User role required"],
  },});

How can I make the role field as an array of two items -admin and manager, where the user can only choose between those two options?

CodePudding user response:

Try using enum like so

  role: {
   type: String,
   enum: ["manager", "admin"],
   default: "manager",
  }
  • Related