Changing mongo database
Asked Answered
G

1

5

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

});
Geomorphology answered 8/5, 2015 at 10:5 Comment(1)
You can get different dbs as follows : var mongoclient = new MongoClient(.....); var admin = mongoclient.db('admin'); var products = mongoclient.db('products'); ....Claudianus
E
24

From MongoDB 2.0.0 Driver docs

Indirectly Against Another Database

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

});
Elstan answered 8/5, 2015 at 10:42 Comment(1)
great, thank you! Couldn't find what you referenced so I'm glad to stumble upon your answer - perfect!Aliquant

© 2022 - 2024 — McMap. All rights reserved.