更改mongo数据库 [英] Changing mongo database
问题描述
我想使用本机2.0 mongodb驱动程序为节点查询副本集中的集合.我可以连接admin
数据库并通过身份验证,但是如何切换数据库以查询我感兴趣的集合?
I want to query a collection in my replica set using the native 2.0 mongodb driver for node. I can connect and authenticated against the admin
database but how do I switch databases to query the collection I'm interested in?
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = "mongodb://user:pass@db1,db2,db3/admin";
MongoClient.connect(url, function(err, db) {
console.log("Connected correctly to server");
console.log("Current database", db.databaseName);
// switch context to database foo
// foo.bar.findOne();
db.close();
});
推荐答案
From MongoDB 2.0.0 Driver docs
间接针对另一个数据库
在某些情况下,您可能必须针对要连接的数据库进行身份验证.这称为委托身份验证.假设您希望连接到foo数据库,但该用户是在admin数据库中定义的.让我们看看我们将如何实现这一目标.
In some cases you might have to authenticate against another database than the one you intend to connect to. This is referred to as delegated authentication. Say you wish to connect to the foo database but the user is defined in the admin database. Let’s look at how we would accomplish this.
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = "mongodb://user:pass@db1,db2,db3/foo?authSource=admin";
MongoClient.connect(url, function(err, db) {
console.log("Connected correctly to server");
console.log("Current database", db.databaseName);
//db==foo
db.close();
});
这篇关于更改mongo数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!