node.js - 如何使用 NodeJS 以 super 用户身份连接到另一个 MongoDB 数据库?

标签 node.js security mongodb

this problem的解决方案工作正常:

而不是做:

$ mongo my_db_name -u superuser -p 1234

我愿意

$ mongo admin -u superuser -p 1234 # connecting as super user to admin db
> use anotherDb

在外壳中。


NodeJS 中的解决方案是什么?

我尝试连接到 mongodb://superuser:1234@localhost:27017/my_db_name 但出现此错误:

{ [MongoError: auth fails] name: 'MongoError', code: 18, ok: 0, errmsg: 'auth fails' }

我的代码是:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://superuser:1234@localhost:27017/my_db_name",
    function(err, db) {
       if (err) { return console.log(err); }
       console.log("Successfully connected.");
    }
); 

请注意, super 用户 是可以在任何 数据库中写入读取 权限的全能用户。 p>

如果我执行 MongoClient.connect("mongodb://superuser:1234@localhost:27017/admin(将 my_db_name 替换为 admin ) 它连接成功。为什么?

如何使用 superuser 和密码 (1234) 连接到 my_db_name

最佳答案

一种解决方案是使用从 Nodejs 端执行的 shell 脚本:

mongo <<EOF
use admin
db.auth("superuser", "1234");
use another_db
db.addUser({
   user: "test",
   pwd: "12345",
   roles: ["userAdmin"]
});
exit
EOF

然后我可以使用以下连接字符串:"mongodb://test:12345@localhost:27017/my_db_name"

此解决方案有效,但我仍在寻找 Mongo native 解决方案。

关于node.js - 如何使用 NodeJS 以 super 用户身份连接到另一个 MongoDB 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20563429/

相关文章:

javascript - Node.js 调用 json 数据时出现问题

android - 当新消息发送给用户并且应用程序处于后台时,我没有收到推送通知

javascript - 未捕获的语法错误 : Unexpected token < VM105:17Uncaught ReferenceError: System is not defined

PHP:$_FILES 中 'type' 索引的来源是什么?

javascript - 如何从另一个模型中找到另一个模型值?

security - 服务器到服务器 REST API 安全性

macos - Swift 中的 Cocoa 授权

mongodb - 将变量传递给 MongoDB View

c# - 更新 MongoDB 集合中的条目

node.js - 将产品插入子模式需要很长时间?