MongoError: there are no users authenticated
Asked Answered
D

2

11

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"
     }
   }
 }
Diapause answered 7/1, 2018 at 14:27 Comment(0)
D
8

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!
   ....
   ........
Diapause answered 7/1, 2018 at 16:5 Comment(0)
C
0

in my case this error came due to wrong db configuration.

my db was set with username and password, but mongoose tried to connect without them, so getting those errors.

const databaseUrl = auth
  ? `mongodb://${username}:${password}@${host}:${port}/${name}` //if with auth
  : `mongodb://${host}:${port}/${name}`; //without auth
Clockwise answered 24/2, 2021 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.