针对多种用户类型的MongoDB架构设计

Dea*_*ift 6 database-design mongodb database-schema

我即将构建一个Node.js + Express + Mongoose应用程序,我想选择社区的大脑,并获得有关最佳实践的建议,并开始创建有效的架构设计.

我的应用程序将包括2种不同的用户类型,即"老师"和"学生".每个都有一个用户配置文件,但每个帐户类型需要不同的字段."老师"和"学生"之间也会有关系,其中"学生"最初将有1名教师(将来可能有更多),而"老师"将有很多学生.

我对如何处理这个问题的初步想法是为每个用户类型(studentProfile模型和teacherProfile模型)创建一般用户模型和配置文件模型,然后在User模型中引用相应的配置文件模型,如下所示(A):

var UserSchema = new Schema({
    name: String,
    email: String,
    password: String,
    role: String, /* Student or Teacher */
    profile: { type: ObjectID, refPath: 'role' }
});

var studentProfileSchema = new Schema({
    age: Number,
    grade: Number,
    teachers: [{ type: ObjectID, ref: 'Teacher' }] 
});

var teacherProfileSchema = new Schema({
    school: String,
    subject: String 
});
Run Code Online (Sandbox Code Playgroud)

或者我只是继续直接在User模型中嵌入两个配置文件的所有字段,然后只填充特定用户类型所需的字段,如下所示(B):

var UserSchema = new Schema({
    name: String,
    email: String,
    password: String,
    role: String, /* Student or Teacher */
    profile: {
       age: Number,
       grade: Number,
       school: String,
       subject: String
    },
    relationships: [{ type: ObjectID, ref: 'User' }]
});
Run Code Online (Sandbox Code Playgroud)

选项B的缺点是我无法真正使用Mongoose 所需的字段.但是,我是否应该首先依靠Mongoose进行验证并让我的应用程序逻辑进行验证?

最重要的是,还会有用于记录学生的活动和任务,参考学生的ID为每个记录的任务,即一个单独的集合/型号:

var activitySchema = new Schema({
    activity: String,
    date: Date,
    complete: Boolean,
    student_id: ObjectID
});
Run Code Online (Sandbox Code Playgroud)

我是否在数据库设计的正确轨道上?任何反馈将非常感激,因为我重视来自这个社区的任何意见,并且我总是希望学习和提高我的技能.有什么比志同道合的个人和该领域的专家更好的方式:)

此外,你可以看到我正在利用Mongoose的人口特征.有什么理由反对这个吗?

再次感谢!

小智 0

您可以尝试使用.discriminator({...})函数来构建用户模式,以便其他模式可以直接“继承”属性。

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
Run Code Online (Sandbox Code Playgroud)

检查文档。