【问题标题】:Student, teacher one common model or two separate ones in mongoose?学生,老师一个普通的模型还是两个单独的猫鼬模型?
【发布时间】:2021-05-05 12:11:03
【问题描述】:

我需要为学生和老师创建一个帐户。我应该在猫鼬中为学生和老师创建两个单独的模型吗?什么是正确的方法?学生和老师将共享一些属性,而另一些则不同。

目前我只有一个学生和导师模型:

const userSchema = new Schema({
    name: {
        type: String,
        trim: true,
        required: true,
        maxLength: 32
    },
    surname: {
        type: String,
        trim: true,
        required: true,
        maxLength: 32
    },
    email: {
        type: String,
        unique: true,
        trim: true,
        required: true,
        lowercase: true
    },
    isActiveTutor: {
        type: Boolean,
        default: false
    },
    birthCountry: String,
    initials: String,
    hashed_password: {
        type: String,
        required: true
    },
    salt: String,
    role: {
        type: String
    },
    teachingLanguage:{
        type: Object,
        /*language: {
            language,
            level,
            price
        }*/
    },
    resetPasswordLink: {
        data: String,
        default: ''
    }
}, {timestamps: true});

但是如果我想给老师一些学生没有的属性呢?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    万一有人经过这里。

    const options = {discriminatorKey: 'kind'};
    
    const userSchema = new mongoose.Schema({/* user schema: (Common) */}, options);
    const User = mongoose.model('User', userSchema);
    
    // Schema that inherits from User
    const Teacher = User.discriminator('Teacher',
      new mongoose.Schema({/* Schema specific to teacher */}, options));
    const Student = User.discriminator('Student',
      new mongoose.Schema({/* Schema specific to student */}, options));
    
    const teacher = new Teacher({/*  */});
    const student = new Student({/*  */});
    

    原始答案(已修改):here。 查看文档here

    【讨论】:

      最近更新 更多