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

Ove*_*d D 15 mongodb node.js

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));
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*ias 33

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

#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
  });
});
Run Code Online (Sandbox Code Playgroud)

#2

文档MongoClient.connect
文档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
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,经过一些挖掘之后,似乎认证的唯一方法是在数据库级别,而不是服务器.所以这是有道理的.我和#2一起去了. (2认同)

Max*_*kiy 5

感谢马蒂亚斯的正确答案。

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

例如,假设您有来自 database 的管理员凭据admin,并且想要连接到 database 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();
    ...

})();
Run Code Online (Sandbox Code Playgroud)

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

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

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