MongoError: there are no users authenticated

↘锁芯ラ 提交于 2020-06-25 09:38:06

问题


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"
     }
   }
 }

回答1:


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!
   ....
   ........


来源:https://stackoverflow.com/questions/48138124/mongoerror-there-are-no-users-authenticated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!