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

これにユーザー名とパスワードをどのように指定しますか?

4

2 に答える 2

37

これを行うには2つの異なる方法があります

#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
});
于 2012-12-26T21:17:01.407 に答える