首页 > 解决方案 > MongoDB如何使用猫鼬模式将角色连接到用户

问题描述

我想构建一个应用程序,用户可以注册为“私人”或“公司”,如果用户注册为公司,他们将有更多选择,例如“包 1”、“包 2”、“包 3”等。这些附加选项是不同的“角色”。

我正在考虑这里的最佳做法。我正在使用MongoDB,所以我应该创建一个包含所有内容的“UserSchema”还是应该创建某种“RoleSchema”?

到目前为止,我有这样的事情:

用户.js:

const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  roleType: {
   type: Schema.Types.ObjectId,
   ref: "roles"
  }
});

module.exports = User = mongoose.model("users", UserSchema);

角色.js

const RoleSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  role_name: {
    type: String
  }
});

module.exports = Roles = mongoose.model("roles", RoleSchema);

这是一个好方法还是可能有其他更好的方法来做到这一点?我对 MongoDB 有点陌生

提前致谢

标签: jsonmongodbnosqlmongoose-schema

解决方案


推荐阅读