How to create an object for a specific user role in mongoose?

Viewed 274

Hey guys I'm trying to build a User Schema that has a role object like this and an appointment object

new mongoose.Schema({
role: {
    type: String,
    enum: ["admin", "partner", "basic"],
    default: "basic",
  },
apponitments: {
    type: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Appointment",
      },
    ],
    required: function () {
      return this.role === "partner";
    },
  }
})

my problem with this code is that no matter what the role is the appointment object is being created anyways.

I don't want this behavior is there a way to stop it ?

1 Answers
  • set default property to undefined when role is admin otherwise return value,
  • se required property to true when role is admin otherwise required false
new mongoose.Schema({
    role: {
        type: String,
        enum: ["admin", "partner", "basic"],
        default: "basic"
    },
    apponitments: {
        type: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: "Appointment"
            }
        ],
        default: function () {
            return this.role === "admin" ? undefined : this.value;
        },
        required: function () {
            return this.role === "admin" ? false : true;
        }
    }
})
Related