如何使用NodeJS以超级用户身份连接到另一个MongoDB数据库? [英] How to connect to another MongoDB database as superuser using NodeJS?
问题描述
此问题的解决方案效果很好:
代替:
$ 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.");
}
);
请注意,超级用户是无所不能的用户,可以在任何数据库中写入和读取权限.>
如果我执行MongoClient.connect("mongodb://superuser:1234@localhost:27017/admin
(用admin
替换my_db_name
),则说明连接成功.为什么?
如何使用superuser
和密码(1234
)连接到my_db_name
?
一种解决方案是使用从Node.js端执行的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本地解决方案.
The solution to this problem works fine:
Instead of doing:
$ mongo my_db_name -u superuser -p 1234
I do
$ mongo admin -u superuser -p 1234 # connecting as super user to admin db
> use anotherDb
in shell.
Which is the solution in NodeJS?
I tried to connect to mongodb://superuser:1234@localhost:27017/my_db_name
but I get this error:
{ [MongoError: auth fails] name: 'MongoError', code: 18, ok: 0, errmsg: 'auth fails' }
My code is:
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.");
}
);
Note that superuser is the omnipotent user that can write and read rights in any database.
If I do MongoClient.connect("mongodb://superuser:1234@localhost:27017/admin
(replaced my_db_name
with admin
) it connects successfully. Why?
How can I connect to the my_db_name
using superuser
and the password (1234
)?
A solution would be to use a shell script that is executed from Nodejs side:
mongo <<EOF
use admin
db.auth("superuser", "1234");
use another_db
db.addUser({
user: "test",
pwd: "12345",
roles: ["userAdmin"]
});
exit
EOF
Then I am able to use the following connection string: "mongodb://test:12345@localhost:27017/my_db_name"
.
This solution works, but I am still looking for the Mongo native solution.
这篇关于如何使用NodeJS以超级用户身份连接到另一个MongoDB数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!