MongoDB schema design for multiple user types MongoDB schema design for multiple user types mongodb mongodb

MongoDB schema design for multiple user types


You could try using .discriminator({...}) function to build the User schema so the other schemas can directly "inherit" the attributes.

const options = {discriminatorKey: 'kind'};const UserSchema = new Schema({    name: String,    email: String,    password: String,    /* role: String, Student or Teacher <-- NO NEED FOR THIS. */    profile: { type: ObjectID, refPath: 'role' }}, options);const Student = User.discriminator('Student', new Schema({    age: Number,    grade: Number,    teachers: [{ type: ObjectID, ref: 'Teacher' }]}, options));const Teacher = User.discriminator('Teacher', new Schema({    school: String,    subject: String}, options));const student = new Student({    name: "John Appleseed",    email: "john@gmail.com",    password: "123",    age: 18,    grade: 12,    teachers: [...]});console.log(student.kind) // Student

Check the docs.