Reputation: 6033
I'm trying to write a code in Node.JS that grant roles to users in MongoDB. I know a way via the CLI:
db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )
How can i do it through Node.JS?
Thanks
Upvotes: 0
Views: 961
Reputation: 1
Yes, it's confusing, the mongo driver only seems to implement the addUser and removeUser functions. Nevertheless, you can use the 'command' function of the mongo driver to access the functions available in the mongo shell. This works for me on mongo 3.4:
...
const db = client.db('admin').admin();
const theRoles = [{role:'readWrite', db: 'someDB'}]
await db.command({grantRolesToUser: 'theUsername', roles: theRoles});
...
The documentation of the command function is rather opaque, and I had to use trial and error to find the proper syntax.
Upvotes: 0
Reputation: 36319
I don't know that it's the only way, but the only thing I can see in the docs is to grant a role when you 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();
});
});
});
});
Upvotes: 1