2015-12-21 53 views
0

我想创建一个可以读取本地数据库的mongo用户。我尝试在本地数据库上使用命令:创建有权读取本地数据库的mongo用户

db.createUser(
    {  user: "readonlyuser", pwd: "loh8Ephi", 
    roles: [ { role: "read", db: "local" } ] 
}) 

但是 - 它不起作用。我收到:

connecting to: local 
2015-12-21T14:08:07.904+0100 Error: couldn't add user: Cannot create users in the local database at src/mongo/shell/db.js:1054 

我试图创建针对管理数据库用户:

> use admin 
switched to db admin 
> db.createUser(
... {  user: "readonlyuser", pwd: "loh8Ephi", roles: [ { role: "read", db: "local" } ] }) 

Successfully added user: { 
"user" : "readonlyuser", 
"roles" : [ 
    { 
     "role" : "read", 
     "db" : "local" 
    } 
] 

,现在我尝试连接:

[email protected]:~$ mongo -u readonlyuser -p loh8Ephi local 
MongoDB shell version: 2.6.11 
connecting to: local 
2015-12-21T15:35:19.190+0100 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1292 
exception: login failed 

如何创建谁拥有只读用户只能访问本地数据库?

回答

2

根据documentation,您不能在本地数据库上创建用户。相反,你可以对admin数据库运行createUser查询:

use admin 
db.createUser(
{  user: "readonlyuser", pwd: "loh8Ephi", 
    roles: [ { role: "read", db: "local" } ] 
}) 

请注意,您必须在连接时对admin数据库进行身份验证。

+0

好了,我已经创建了一个用户管理数据库: >使用管理 切换到数据库管理员 > db.createUser( ... {用户: “readonlyuser” PWD “loh8Ephi”,角色:[{作用: “读”,分贝: “本地”}]}) 成功添加用户:{ \t “用户”: “readonlyuser”, \t“角色“:[ \t \t { \t \t \t “角色”: “读”, \t \t \t “DB”: “本地” \t \t} \t] 现在我尝试连接: 取消定义@机:〜$蒙戈-u readonlyuser - p loh8Ephi本地 MongoDB shell版本:2.6.11 连接到:本地 2015-12-21T15:35:19.190 + 0100错误:18 {ok:0.0,errmsg:“auth failed”,code:18} at src/mongo/shell/db.js:1292 异常:登录失败 – undefine

+0

您需要对'admin'数据库进行身份验证。 – Jaco

+0

好吧,它的工作原理,但是...那么该用户有权连接到管理数据库: undefine @ undefine -ThinkPad-T430s:〜$ mongo -u readonlyuser -p loh8Ephi --authenticationDatabase admin admin MongoDB shell版本: 2.6.11 连接到:admin 我想创建只有本地,而不是管理数据库的用户:-) – undefine

1

我会做类似下面

use admin 
db.getSiblingDB("local").runCommand({ "createUser" : "mongoread", "pwd": "read0nly", "customData" : { "description": "mongo readonly user" }, "roles" : [ {"role" : "read","db" : "local"}] },{ w: "majority" , wtimeout: 5000 });