【发布时间】:2016-11-19 17:05:45
【问题描述】:
我正在尝试在 Node.JS 中编写代码,将角色授予 MongoDB 中的用户。 我知道通过 CLI 的方法:
db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )
如何通过 Node.JS 实现?
谢谢
【问题讨论】:
我正在尝试在 Node.JS 中编写代码,将角色授予 MongoDB 中的用户。 我知道通过 CLI 的方法:
db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )
如何通过 Node.JS 实现?
谢谢
【问题讨论】:
我不知道这是唯一的方法,但我在文档中看到的唯一内容是当您 add a user 时授予角色。
var MongoClient = require('mongodb').MongoClient,
test = require('assert'); MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
// Use the admin database for the operation
var adminDb = db.admin();
// Add the new user to the admin database
adminDb.addUser('admin11', 'admin11', {roles : ['blah']}, function(err, result) {
// Authenticate using the newly added user
adminDb.authenticate('admin11', 'admin11', function(err, result) {
test.ok(result);
adminDb.removeUser('admin11', function(err, result) {
test.ok(result);
db.close();
});
});
});
});
【讨论】:
是的,这很令人困惑,mongo 驱动程序似乎只实现了 addUser 和 removeUser 函数。不过,您可以使用 mongo 驱动程序的“命令”功能来访问 mongo shell 中可用的功能。这适用于 mongo 3.4:
...
const db = client.db('admin').admin();
const theRoles = [{role:'readWrite', db: 'someDB'}]
await db.command({grantRolesToUser: 'theUsername', roles: theRoles});
...
命令函数的文档相当不透明,我不得不通过反复试验来找到正确的语法。
【讨论】: