[MongoDB]-权限验证管理
// 连接到MongoDB数据库
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
// 创建新的MongoClient实例
const client = new MongoClient(url, { useUnifiedTopology: true });
// 连接到数据库
async function connectToDatabase() {
try {
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
return db;
} catch (err) {
console.error('Cannot connect to database', err);
throw err;
}
}
// 创建用户并赋予角色
async function createUserAndAssignRole(db) {
try {
const user = await db.createUser({
user: 'myUser',
pwd: 'myPassword',
roles: [{ role: 'readWrite', db: 'mydatabase' }]
});
console.log('User created successfully', user);
} catch (err) {
console.error('Cannot create user', err);
throw err;
}
}
// 更新用户的角色
async function updateUserRole(db) {
try {
const user = await db.updateUser('myUser', {
roles: [{ role: 'read', db: 'mydatabase' }]
});
console.log('User role updated successfully', user);
} catch (err) {
console.error('Cannot update user role', err);
throw err;
}
}
// 删除用户
async function deleteUser(db) {
try {
const result = await db.dropUser('myUser');
console.log('User deleted successfully', result);
} catch (err) {
console.error('Cannot delete user', err);
throw err;
}
}
// 使用示例
async function run() {
const db = await connectToDatabase();
await createUserAndAssignRole(db);
await updateUserRole(db);
await deleteUser(db);
client.close();
}
run().catch(console.error);
这段代码展示了如何在MongoDB中创建用户、为用户赋予角色、更新用户的角色,以及删除用户。它使用了异步函数和try-catch
块来处理错误,并在操作完成后关闭了数据库连接。
评论已关闭