How to connect to another MongoDB database as root using NodeJS?

Solving this problem works fine:

Instead of this:

$ mongo my_db_name -u superuser -p 1234

I do

$ mongo admin -u superuser -p 1234 # connecting as super user to admin db
> use anotherDb

in the shell.


What is the solution in NodeJS?

I tried to connect to mongodb://superuser:1234@localhost:27017/my_db_name, but I get this error:

{ [MongoError: auth fails] name: 'MongoError', code: 18, ok: 0, errmsg: 'auth fails' }

My code is:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://superuser:1234@localhost:27017/my_db_name",
    function(err, db) {
       if (err) { return console.log(err); }
       console.log("Successfully connected.");
    }
); 

Please note that the superuser is an omnipotent user who can write and read rights in any database.

If I do MongoClient.connect("mongodb://superuser:1234@localhost:27017/admin(replaced my_db_nameby admin), it connects successfully. Why?

How to connect to my_db_namewith superuserand password ( 1234)?

+4
source share
2 answers

script, Nodejs:

mongo <<EOF
use admin
db.auth("superuser", "1234");
use another_db
db.addUser({
   user: "test",
   pwd: "12345",
   roles: ["userAdmin"]
});
exit
EOF

: "mongodb://test:12345@localhost:27017/my_db_name".

, Mongo.

+3

Db().db(dbname) Db, .

, admin db another_db:

db.auth("superuser", "1234");
another_db = db.db("another_db");
another_db.addUser({...}
+3

All Articles