arrays - 在 MongoDB 中设置角色
问题描述
我正在建模和播种我的User
模型,基本上我提出了 3 种类型的角色regular
:shop_owner
和admin
. admin 显然可以添加店铺,访问用户,而 shop_owner 只能添加店铺。而普通用户只能对店主创建的店铺发表评论。
在我的User
模型上,我创建了这个设置:
const userSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
phone: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
isAdmin: {
type: Boolean,
required: true,
default: false
},
roles: {
type:[String],
required: true,
default: ["regular"]
}
}, { timestamps: true
})
const User = mongoose.model('User', userSchema)
export default User
正如您在此处看到的,我放置了一个关键字段isAdmin
来检查用户是否是管理员,同时还有一个roles
数组,用户可以在其中选择任一角色。
然后在我的种子文件上:
const users = [
{
name: 'Rodel Buan',
email: 'info@example.com',
password: bcrypt.hashSync('123456', 10),
isAdmin: true,
phone: '230 000 2000',
},
{
name: 'Nick Smith',
email: 'info@example.com',
password: bcrypt.hashSync('123456', 10),
isAdmin: true,
phone: '230 000 2000',
roles: 'regular'
},
{
name: 'Maine Oscopo',
email: 'info@example.com',
password: bcrypt.hashSync('123456', 10),
isAdmin: true,
phone: '230 000 2000',
roles: 'shop_owner'
}
]
当我将它插入我的种子时,它会显示如下内容:
{
"_id":{
"$oid":"5fc1e13a5825d81308e93555"
},
"isAdmin":true,
"roles":[
"reviewer"
],
"name":"Rodel Buan",
"email":"info@example.com",
"password":"$2a$10$tUkhp54un.Qev6JWklqMG.FBvQbhgQNr.5N2rEVrkmFfX/EAnwyiO",
"phone":"230 000 2000",
"__v":0,
"createdAt":{
"$date":"2020-11-28T05:33:46.281Z"
},
"updatedAt":{
"$date":"2020-11-28T05:33:46.281Z"
}
}{
"_id":{
"$oid":"5fc1e13a5825d81308e93556"
},
"isAdmin":false,
"roles":[
"regular"
],
"name":"Nick Smith",
"email":"info@example.com",
"password":"$2a$10$bLpGlXFO5UatEfp2Y2bWjuX2vQ8WXCsJ9AeiP3Edlmw2HHuXii/3y",
"phone":"230 000 2000",
"__v":0,
"createdAt":{
"$date":"2020-11-28T05:33:46.281Z"
},
"updatedAt":{
"$date":"2020-11-28T05:33:46.281Z"
}
}{
"_id":{
"$oid":"5fc1e13a5825d81308e93557"
},
"isAdmin":false,
"roles":[
"shop_owner"
],
"name":"Maine Oscopo",
"email":"info@example.com",
"password":"$2a$10$f6laIJNEaL0Jscyptljbt.Vz.rPO.5LJWHXpmsqkWO6KSd5DFX/jm",
"phone":"230 000 2000",
"__v":0,
"createdAt":{
"$date":"2020-11-28T05:33:46.281Z"
},
"updatedAt":{
"$date":"2020-11-28T05:33:46.281Z"
}
}
看着roles
我想知道我是否正确处理了这类用户?或者有没有更好的方法来处理这个问题,而不是将isAdmin
角色放在字符串数组中。因为稍后当我列出所有用户(包括授权设置)时,我将把它放在后端。
解决方案
推荐阅读
- java - 从控制台输入动态创建数组
- python - 在没有for循环的情况下对Numpy数组进行连续的一对多计算的快速方法?
- javascript - 如何在没有 jQuery 的情况下使 AJAX 请求同步?
- grails - grails 4,url映射中的parseRequest不起作用
- mysql - 错误 1093,但子查询中没有选择
- angular - 如何将依赖订阅映射到对象列表中,其中包含来自每个订阅的数据组合?
- python - eth_keys 如何获取字符串公钥以便我可以将其放入 JSON
- recursion - Kotlin尾递归函数导致堆栈溢出
- laravel-5 - How to access the parent data eloquent join
- ruby-on-rails - Active Record 包含belongs_to 和has_many 不返回关联