2012-12-26 19 views
10

MongoClientドキュメントには、接続を作成するには、Serverインスタンスを使用する方法を示しています。Serverインスタンスを使用してmongodbのユーザ名とパスワードを指定する方法はありますか?

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

はどのようにこのためのユーザー名とパスワードを指定するのでしょうか?

答えて

26

あなたはこの

#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を行うことができる2つの異なる方法があります
Documentation The URL
A私ははるかに気に入っています。読むのがもっと小さくて簡単だからです。

// Just this code nothing more 

var MongoClient = require('mongodb').MongoClient; 
MongoClient.connect("mongodb://username:[email protected]:27017/exampledatabase", function(err, db) { 
    // Now you can use the database in the db variable 
}); 
+1

まあ、掘り下げた後は、認証する唯一の方法はサーバーではなく、データベースレベルであるようです。だからこれは理にかなっている。私は#2と一緒に行きました。 –

1

正解のためにMattiasに感謝します。

別のデータベースに接続する際に、あるデータベースから資格情報を取得することがあることを追加したいと思います。 その場合でも、URLに?authSource=パラメータを追加するだけで、URL方法を使用して接続できます。

たとえば、データベースadminからの管理者の資格情報があり、データベースmydbに接続したいとします。パスワードに特殊文字が含まれている場合、あなたはまだ、このようにURLの方法を使用することができ、また

const MongoClient = require('mongodb').MongoClient; 

(async() => { 

    const db = await MongoClient.connect('mongodb://adminUsername:[email protected]:27017/mydb?authSource=admin'); 

    // now you can use db: 
    const collection = await db.collection('mycollection'); 
    const records = await collection.find().toArray(); 
    ... 

})(); 

:あなたはそれを次のように操作を行うことができ

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

注:以前のバージョンでは、{ uri_decode_auth: true }オプションが必要とされましたユーザー名またはパスワードにencodeURIComponentを使用するときは、(connectメソッドの2番目のパラメータとして)、このオプションは廃止されました。

関連する問題