5

The solution to this problem works fine:

Instead of doing:

$ 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 shell.


Which 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.");
    }
); 

Note that superuser is the omnipotent user that can write and read rights in any database.

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

How can I connect to the my_db_name using superuser and the password (1234)?

2 Answers 2

4

A solution would be to use a shell script that is executed from Nodejs side:

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

Then I am able to use the following connection string: "mongodb://test:12345@localhost:27017/my_db_name".

This solution works, but I am still looking for the Mongo native solution.

Sign up to request clarification or add additional context in comments.

1 Comment

I added a native solution which should work for you. By the way, if you are still looking for a better answer for a question you should leave it unaccepted to increase the chances someone else will notice the question :).
4

You can use the Db().db(dbname) method to create a new Db instance sharing the same connection.

So you can authenticate to the admin db and change to another_db:

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

3 Comments

But is this the NodeJS solution? I guess it's a Mongo script... Can you edit your answer providing a small NodeJS script that connects Mongo database as superuser?
@IonicăBizău: That's the NodeJS solution .. have a look at the DB().db() documentation that I linked :).
I remember that I tried that but it didn't work. That's why I ask for full script to be able to test it. If you solve the problem I will accept your answer happilly. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.