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

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

推荐答案

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

#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
A way I like much more because it is smaller and easier to read.

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

Mongodb相关问答推荐

MongoDB更新对象数组

为什么数组长度0被认为是Mongoose中排序中最大的数字

所有文档中嵌套 struct 中的条件匹配-mongodb

在对象mongodb的数组中查找元素

Mongoose updateMany 以及 Where 和 orWhere?

尽管前一阶段输出文档,$group stage 仍返回零文档

在亚马逊 EC2 上托管 nodeJS/mongoose Web 应用程序

Spring Data + MongoDB GridFS 可以通过 Repository 访问吗?

node.js & express - 应用程序 struct 的全局模块和最佳实践

pymongo 排序和 find_one 问题

django 和 mongodb 是否使迁移成为过go ?

在 Mongo 中存储嵌套类别的最有效方法?

是否有适用于 Linux 的 MongoDB GUI 桌面应用程序?

Mongoose 连接认证失败

无法从 MongoDb C# 中的 BsonType ObjectId 反序列化字符串

如何从 node.js 以编程方式执行 mongodump 命令?

NumberLong和简单整数之间的MongoDB区别?

Mongo:无法在 src/mongo/shell/mongo.js:145 连接到服务器 127.0.0.1:27017

Lombok - java.lang.StackOverflowError:toString 方法上的 null

停止副本集 MongoDB