【问题标题】:How can you specify the mongodb username and password using a Server instance?如何使用服务器实例指定 mongodb 用户名和密码?
【发布时间】:2012-12-12 07:15:04
【问题描述】:

MongoClient 文档展示了如何使用服务器实例来创建连接:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server;

// Set up the connection to the local db
var mongoclient = new MongoClient(new Server("localhost", 27017));

您将如何为此指定用户名和密码?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    感谢 Mattias 的正确回答。

    我想补充一点,有时您在想要连接到另一个数据库时拥有来自一个数据库的凭据。 在这种情况下,您仍然可以使用 URL 方式连接,只需在 URL 中添加?authSource= 参数即可。

    例如,假设您拥有来自数据库 admin 的管理员凭据,并且想要连接到数据库 mydb。您可以通过以下方式进行:

    const MongoClient = require('mongodb').MongoClient;
    
    (async() => {
    
        const db = await MongoClient.connect('mongodb://adminUsername:adminPassword@localhost:27017/mydb?authSource=admin');
    
        // now you can use db:
        const collection = await db.collection('mycollection');
        const records = await collection.find().toArray();
        ...
    
    })();
    

    另外,如果您的密码中包含特殊字符,您仍然可以像这样使用 URL 方式:

        const dbUrl = `mongodb://adminUsername:${encodeURIComponent(adminPassword)}@localhost:27017/mydb?authSource=admin`;
        const db = await MongoClient.connect(dbUrl);
    

    注意:在早期版本中,{ uri_decode_auth: true } 选项是必需的(作为 connect 方法的第二个参数)当使用 encodeURIComponent 作为用户名或密码时,但是现在这个选项已经过时,没有它也可以正常工作。

    【讨论】:

      【解决方案2】:

      有两种不同的方法可以做到这一点

      #1

      Documentation(注意文档中的例子使用了Db对象)

      // Your code from the question
      
      // Listen for when the mongoclient is connected
      mongoclient.open(function(err, mongoclient) {
      
        // Then select a database
        var db = mongoclient.db("exampledatabase");
      
        // Then you can authorize your self
        db.authenticate('username', 'password', function(err, result) {
          // On authorized result=true
          // Not authorized result=false
      
          // If authorized you can use the database in the db variable
        });
      });
      

      #2

      Documentation MongoClient.connect
      Documentation The URL
      一种我更喜欢的方式,因为它更小更易于阅读。

      // Just this code nothing more
      
      var MongoClient = require('mongodb').MongoClient;
      MongoClient.connect("mongodb://username:password@localhost:27017/exampledatabase", function(err, db) {
        // Now you can use the database in the db variable
      });
      

      【讨论】:

      • 是的,经过一番挖掘,似乎唯一的身份验证方法是在数据库级别,而不是服务器。所以这是有道理的。我选择了#2。
      • @Mattias - 如果有变化,请检查 - stackoverflow.com/questions/54442315/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2011-06-20
      • 1970-01-01
      • 2021-11-29
      • 2020-07-17
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多