MongoError: there are no users authenticated

MongoError: there are no users authenticated

我正在尝试使用 mongodb NodeJS 驱动程序 - 版本 3.0.1[= 编写脚本以将管理员用户和普通用户添加到 MongoDB 数据库29=]

我可以为数据库创建管理员用户,但不能创建普通用户。我总是得到 MongoError: there are no users authenticated。通过文档,验证用户身份的唯一方法是通过 URL。我已经把指定路径下的数据库彻底删除了,试了好多次,还是卡住了。

这是我目前得到的,

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;
        });
      });
   });
 });

这是我的 mongod.cfgmongod 进程的配置文件:

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

最后是配置文件,config.json:

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

通过先关闭客户端然后再次连接到 MongoDB 解决了这个问题。这次使用 connect 返回的新 client

上面代码的相关部分是:

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

在我的例子中,这个错误是由于错误的数据库配置造成的。

我的数据库设置了用户名和密码,但 mongoose 试图在没有它们的情况下进行连接,所以出现了这些错误。

const databaseUrl = auth
  ? `mongodb://${username}:${password}@${host}:${port}/${name}` //if with auth
  : `mongodb://${host}:${port}/${name}`; //without auth