大佬教程收集整理的这篇文章主要介绍了node.js – MongoError:没有用户通过身份验证,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以创建管理员用户,但不能创建数据库的普通用户.我总是得到MongoError:没有用户通过身份验证.通过文档,验证用户的唯一方法是通过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)),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"
{ "database": { "LOCATIOn": "localhost","name": "mongodb-test","port": 27017,"auth": { "username": "testuser","password": "welcome" } } }
以上代码的相关部分是:
....... ............ adminDb.addUser(adminUser,{ 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,authClient) { if (err) throw err; console.log('Authenticated successfully'); const db = authClient.db() // this is important! .... ........
以上是大佬教程为你收集整理的node.js – MongoError:没有用户通过身份验证全部内容,希望文章能够帮你解决node.js – MongoError:没有用户通过身份验证所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。