node.js - MongoError : there are no users authenticated

标签 node.js mongodb mongoose node-mongodb-native

我正在尝试使用 mongodb NodeJS 驱动程序 - 版本 3.0.1

我可以为数据库创建管理员用户,但不能创建普通用户。我总是收到 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!
   ....
   ........

关于node.js - MongoError : there are no users authenticated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48138124/

相关文章:

javascript - Model.find() 不是函数

javascript - AWS S3 - 我们计算的请求签名与您提供的签名不匹配。检查您的 key 和签名方法

node.js - s3.getSignedUrl ResponseContentDisposition 参数不起作用

node.js - 在特定时间删除Mongoose、Nodejs用户

javascript - 响应中搜索词的匹配列表

javascript - 如何使用monk/node.js调用mongodb函数?

javascript - 如何从方括号内的对象解析字符串

node.js - Node 的包管理器警告

java - 如何从 MongoDB 和 Cosmos DB 的值字段获取可嵌入文档?

python - MongoDB:找到数组中的最小元素并将其删除