简体   繁体   English

如何在 mongoose 中创建一个依赖于另一个枚举的枚举?

[英]How to create an enum dependent on another enum in mongoose?

I have the following schema:我有以下架构:

const doctorSchema = new mongoose.Schema(
{
    specialty: {
        type: String,
        required: false
    },
    subspecialty: {
        type: String,
        required: false
    }
}

A doctor can have a single specialty .一个医生可以有一个专业 For example, a doctor can be a cardiologist or a neurologist.例如,医生可以是心脏病专家或神经科医生。

A doctor can have a single subspecialty , but this is dependent on the original specialty.医生可以有一个subspecialty ,但这取决于原来的专业。 For example, a neurologist can have a subspecialty in neurocritical care, but a cardiologist cannot have a subspecialty in neurocritical care.例如,神经科医生可以拥有神经重症监护的亚专科,但心脏病专家不能拥有神经重症监护的亚专科。

I am trying to model this in the schema.我正在尝试在架构中使用 model。 We can create a schema for specialties:我们可以为专业创建一个模式:

enum specialty {
    cardiologist = 'cardiologist',
    neurologist = 'neurologist'
}

With this, how can I add an enum for subspecialties for each specialty?有了这个,我如何为每个专业添加一个子专业枚举? In other words, I would like to add a list of subspecialties that belong to ONLY a neurologist, a list that only belongs to ONLY cardiologists, etc.换句话说,我想添加一个仅属于神经科医生的子专科列表,一个仅属于心脏病专家的列表,等等。

Mongoose has several built-in validators. Mongoose 有几个内置的验证器。

  • All SchemaTypes have the built-in required validator.所有 SchemaTypes 都有内置的 required 验证器。 The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator.必需的验证器使用 SchemaType 的 checkRequired() function 来确定值是否满足必需的验证器。

  • Numbers have min and max validators.数字有最小和最大验证器。

  • Strings have enum, match, minlength, and maxlength validators.字符串有枚举、匹配、最小长度和最大长度验证器。

For your case you could do something like this对于你的情况,你可以做这样的事情

const doctorSchema = Schema({
 _id: Schema.Types.ObjectId, 
specialty: { type: string, required: true }, 
subspecialty: { 
      type: string, 
      required: function() { 
        if(this.specialty === "neurologist"){
            return {
                enum : ['neurologist-sub-list','neurologist-sub-list2'],
                default: 'neurologist-sub-list',
                message: '{VALUE} is not supported'
             }
        }
      }
  } 
});

you can do the remaining part in the if else block where specailty doesn't satisfy the neurologist你可以在 if else 块中做剩下的部分,其中 specacailty 不满足神经科医生

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM