我正在尝试对正在编写的NodeJS程序实施一种基于角色的访问控制。这些角色将与所有其他数据一起使用Mongoose存储在MongoDB数据库中。为此创建了RoleSchema
。角色的名称类型为String,数组类型为String,其中包含角色权限。我已经在下面发布了该代码。
对于我的API,我要实现三个角色:用户,作者和管理员,每个角色具有不同的权限。在集合中一次创建这些文档的最佳方法是什么?我知道我可以简单地手动创建条目,但是我觉得编程解决方案会更好。就像检查角色是否已经创建,是否创建角色一样简单,还是有更好的方法呢?
const RoleSchema = new Schema({
role: {
type: String,
default: "user",
},
permissions: {
type: [String]
}
})
const RoleModel = mongoose.model('roles',RoleSchema)
RoleModel.create({
role: 'user',
permissions: ['readPost', 'commentPost', 'votePost']
}, (error, result) => {})
答案 0 :(得分:1)
So, Seeding a database is a process in which an initial set of data is provided to a database.
As a best practice instead of manually inserting the data you should configure seed data for automatic insertion of documents.
var seeder = require('mongoose-seed');
// Connect to MongoDB via Mongoose
seeder.connect('mongodb://localhost/yourDatabase', function() {
// Load Mongoose models
seeder.loadModels([
'models/roles.js'
]);
// Clear specified collections
seeder.clearModels(['roles'], function() {
// Callback to populate DB once collections have been cleared
seeder.populateModels(data, function() {
seeder.disconnect();
});
});
});
// Data array containing seed data - documents organized by Model
var data = [
{
'model': 'role',
'documents': [
{
'role': 'user',
'value': ['readPost', 'commentPost', 'votePost']
},{
'role': 'another role',
'value': ['updatePost', 'deletePost']
}
]
}
];
put that code on a seed.js
file and run it.
答案 1 :(得分:1)
Assuming that the role names are unique, you can indeed query the database and check if a role with the same name already exists. If not, we go ahead and create the role.
This works well for me:
const createRole = async ({role, permissions}) => {
const matches = await RoleModel.find({role}).exec();
if (matches.length === 0) {
return RoleModel.create({role, permissions});
}
};
The method can be then invoked in the following way (given that you've already connected to the database):
const userRole = {
role: "User",
permissions: ["readPost", "commentPost", "votePost"]
};
(async () => {
await createRole(userRole);
console.log("User role has been created successfully.");
})()