MongoError: there are no users authenticated

Ozil picture Ozil · Jan 7, 2018 · Viewed 15.7k times · Source

I'm trying to write a script to add an admin user and a generic user to the MongoDB database using mongodb NodeJS driver - version 3.0.1

I'm able to create the admin user, but not general user for a database. I'm always getting MongoError: there are no users authenticated. Going through the documentation, the only way to authenticate a user is via URL. I've deleted the database completely from the specified path, tried multiple times, still, I'm stuck.

Here is what I've got so far,

const MongoClient = require('mongodb').MongoClient;
const format = require('util').format;
const config = require("./config.json");

var adminUser = process.argv[2],
adminPassword = process.argv[3],
url = `mongodb://${config.database.location}:${config.database.port}`,
authURL = `mongodb://%s:%s@${config.database.location}:${config.database.port}/?authMechanism=SCRAM-SHA-1&authSource=admin`;

if (!adminUser || !adminPassword) {
   throw new Error("Please enter administrator username and password!\nUsage:\tnode init.js <adminUserName> <adminPassword>\n\n");
}

MongoClient.connect(url, function (err, client) {
    if (err) throw err;
    console.log("Connected successfully to server");
    const db = client.db(config.database.name);
    var adminDb = db.admin();
    adminDb.addUser(adminUser, adminPassword, {
        roles: [{
           role: "userAdminAnyDatabase",
           db: "admin"
        }]
    }).then(function (err, result) {
            MongoClient.connect(format(authURL, encodeURIComponent(adminUser), encodeURIComponent(adminPassword)), function (err, authClient) {
                  if (err) throw err;
                  console.log('Authenticated Successfully');
                  const db = client.db(config.database.name);
                  var adminDb = db.admin();
                  db.addUser(config.database.auth.username, config.database.auth.password, {
                         roles: [{
                             role: "readWrite",
                             db: config.database.name
                         }]
               }).then(function () {
                   console.log("Setup completed!");
                   authClient.close();
                   client.close();
               }).catch(function (err) {
                   throw err.stack;
        });
      });
   });
 });

Here is my mongod.cfg, the configuration file for mongod process:

systemLog:
      destination: file
      path: D:\MongoDB\logs\mongod.log
storage:
      dbPath: D:\MongoDB\database
security:
      authorization: "enabled"

And finally the configuration file, config.json:

{
  "database": {
    "location": "localhost",
    "name": "mongodb-test",
    "port": 27017,
    "auth": {
        "username": "testuser",
        "password": "welcome"
     }
   }
 }

Answer

Ozil picture Ozil · Jan 7, 2018

Resolved it by closing the client first and then connecting to MongoDB again. This time use the new client returned by connect.

Relevant section from above code is:

.......
............
adminDb.addUser(adminUser, adminPassword, {
    roles: [{
        role: "userAdminAnyDatabase",
        db: "admin"
    }]
}).then(function (result) {
    if (result && result.user) {
        console.log("Admin user created successfully");
        client.close(); // close the previous connection!
    }
    MongoClient.connect(format(authURL, encodeURIComponent(adminUser), encodeURIComponent(adminPassword)), function (err, authClient) {
        if (err) throw err;
        console.log('Authenticated Successfully');
        const db = authClient.db() // this is important!
   ....
   ........