首页 > 解决方案 > 在 MongoDB 中设置角色

问题描述

我正在建模和播种我的User模型,基本上我提出了 3 种类型的角色regularshop_owneradmin. 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角色放在字符串数组中。因为稍后当我列出所有用户(包括授权设置)时,我将把它放在后端。

标签: arraysmongodbmongoose

解决方案


推荐阅读