【问题标题】:how to database design for user authentication like student, teacher , super admin如何为学生、教师、超级管理员等用户身份验证设计数据库
【发布时间】:2019-09-22 23:03:05
【问题描述】:

我正在尝试为 user 创建不同类型的注册。我为用户收集了三个集合。我一直在参考教师和学生的用户集合,因为我需要获取电子邮件和密码。

如果教师注册包括电子邮件、密码、名字、姓氏等,则有一个集合。

如果学生注册包括电子邮件、密码、名字、姓氏等,则有另一个集合。

我们所有的邮箱和密码都将是一个集合

用户 - 表/集合 - 电子邮件:test@gmail.com - 密码:asdfasdf

学生 - 表/集合 - 名字:'sujon'

老师 - 表/集合 - 名字:“sujon”

const UserSchema = mongoose.Schema({
    email: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true,
    },
    isAdmin: {
        type: Boolean,
        default: false,
    },
})


const StudentSchema = mongoose.Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'user',
    },
    firstname: {
        type: String,
    },
    lastname: {
        type: String,
    },
    photo: {
        type: String,
    },
    education: {
        type: String,
    },
    birth: {
        type: Date,
    },
    sex: {
        type: Boolean,
    },
})
  const TeacherSchema = mongoose.Schema({
  user: {
    type: mongoose.Schema.ObjectId,
    ref: "user"
  },
  firstname: {
    type: String
  },
  lastname: {
    type: String
  },
  photo: {
    type: String
  },
  designation: {
    type: String
  },
  birth: {
    type: Date
  },
  sex: {
    type: Boolean
  }
   });

如何实现数据库设计

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    创建单个用户架构就可以了。您可以拥有一个包含所有属性的模式(因为所有三种类型的用户都具有几乎相同的属性),然后添加一个“角色”字段,如下所示:

    roles: [{ type: String }]
    

    角色字段可以有多个角色 ['Teacher', 'Student' ...]。这样一个用户可以拥有多个角色,例如教师也可以是管理员等。

    此外,您不必在引入新角色时创建新模型。

    可以根据角色查询用户。然后这些角色也可以用于身份验证,例如角色为“教师”的用户可以创建作业,或者角色为“学生”的用户可以提交作业。注册用户时,您可以在 api 或客户端设置某种模型验证以接受某个模型。

    【讨论】:

    • 你可以为用户设计模型吗?我有点困惑
    • const UserSchema = mongoose.Schema({ email: { type: String, required: true, }, password: { type: String, required: true, }, roles: [{ type: String }], // All other optional fields. })
    • 如果我使用三个集合进行基于角色的身份验证有什么问题
    • 是的,很少有问题是: 1- 每当您创建一个新角色时,您都必须添加一个新集合。 2-不能为单个用户分配多个角色。 3- 每个集合都有不同的登录功能。
    • 感谢您的 cmets 。你救了我,但现在正在处理角色。如何在身份验证期间使用角色。
    猜你喜欢
    • 2011-12-15
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多