我正在尝试编写一个脚本,使用mongodb
NodeJS驱动程序将管理员用户和通用用户添加到MongoDB数据库 - 版本 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.cfg
,mongod
进程的配置文件:
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"
}
}
}
答案 0 :(得分:2)
首先关闭客户端,然后再次连接到MongoDB,解决了这个问题。这次使用client
返回的新connect
。
以上代码的相关部分是:
.......
............
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!
....
........
答案 1 :(得分:0)
就我而言,此错误是由于数据库配置错误造成的。
我的数据库设置了用户名和密码,但猫鼬试图在没有它们的情况下进行连接,因此出现了这些错误。
const databaseUrl = auth
? `mongodb://${username}:${password}@${host}:${port}/${name}` //if with auth
: `mongodb://${host}:${port}/${name}`; //without auth