Skip to content
Advertisement

mongoose – How can I set the role field with only predefined options

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?

Advertisement

Answer

Try using enum like so

  role: {
   type: String,
   enum: ["manager", "admin"],
   default: "manager",
  }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement