簡體   English   中英

通過 nodejs 在 MongoDB 中授予用戶角色

[英]Grant user roles in MongoDB via nodejs

我正在嘗試在 Node.JS 中編寫一個代碼,為 MongoDB 中的用戶授予角色。 我知道一種通過 CLI 的方法:

db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )

我怎樣才能通過 Node.JS 做到這一點?

謝謝

我不知道這是唯一的方法,但是我在文檔中看到的唯一一件事就是添加用戶時授予角色。

var MongoClient = require('mongodb').MongoClient,

測試= 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});
...

命令函數的文檔相當不透明,我不得不通過反復試驗來找到正確的語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM