如何使用服务器实例指定mongodb用户名和密码?

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

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

你将如何指定一个用户名和密码?

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

#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

文档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 });