如何使用 Server 实例指定 MongoDB 的用户名和密码?

21

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

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));

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

2个回答

37

你可以通过两种不同的方式完成这个任务

#1

文档(请注意,文档中的示例使用了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
是的,在一番搜索后,似乎唯一的身份验证方式是在数据库层面上进行,而不是服务器。所以这很有道理。我选择了第二种方法。 - Oved D
@Mattias - 如果方便的话,请查看此链接:https://stackoverflow.com/questions/54442315/nodejs-mongno-db-connect-with-server-database-with-username-and-password。 - RSKMR

5

感谢Mattias的正确回答。

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

例如,假设您拥有来自数据库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);

注意:在早期版本中,当使用encodeURIComponent对用户名或密码进行编码时,需要将{uri_decode_auth: true}选项作为connect方法的第二个参数传入,但现在此选项已过时,不再需要,可以正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接