1

I need to create an account for a student and a teacher. Should I create two separate models in mongoose for student and teacher? What's the right approach? Student and teacher will share some properties and some will differ.

At this moment I have only one model for student and tutor:

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});

But what if I wanted to give a teacher properties that a student would not have?

Umbro
  • 1,984
  • 12
  • 40
  • 99

1 Answers1

2

In case someone pass by here.

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({/*  */});

Original answer(modified): here. Have a look at the docs here.