具有 readWrite 的 mongoengine 用户无法创建索引

mongoengine user with readWrite can not create indexes

我是 运行 python 2.7 和 mongodb 2.6.5。 我无法让我的 mongo 引擎连接并发出请求,但我可以使用用户登录 mongo 并发出相同的请求。 我像这样在 mongodb 中创建了 3 个用户(密码不是空白,但我已将其删除):

$ mongo campaigns
db.createUser({"user": "admin", "pwd": "", "roles": [
  {"role": "dbOwner", "db":"campaigns" },
  {"role": "dbOwner", "db":"admin" },
  {"role": "readAnyDatabase", "db": "admin" },
   "readWrite" ]},
  { "w": "majority" , "wtimeout": 5000 })

db.createUser({"user": "look", "pwd": "", "roles": ["read"]})
db.createUser({ "user": "write",  "pwd": "", "roles": ["readWrite"]})

然后我使用 python 和 mongo 引擎连接到我的本地 mongo(尝试使用用户写入和用户管理员):

self.db = connect(setting.DB["db"], "db", host=setting.DB["urli"],
                  port=setting.DB["port"], username=setting.DB["user"],
                  password=setting.DB["pwd"])

setting.DB 的打印(同样密码不是空白我只是不写在那里)。

{'urli': 'mongodb://localhost/', 'pwd':, 'db': 'campaigns', 'user': 'melu-write', 'port': 27017}

一切都很好,但是当我尝试 python:

l = [x.name for x in campaign.objects.only("name").all()]

MongoEngine 给我这个错误:

OperationFailure: database error: not authorized for query on campaigns.campaigns

当我从 mongo 登录时,如:

mongo campaigns -u write -p
> password:
> db.campaigns.find()
{ "_id":....

几乎没有错误痕迹:

pymongo.errors.OperationFailure: command SON([('createIndexes', u'campaigns'), ('indexes', [{'name': u'offers.product_name_1', 'key': SON([('offers.product_name', 1)]), 'unique': True, 'background': False, 'sparse': False, 'dropDups': False}])])
on namespace campaigns.$cmd failed: not authorized on campaigns to execute command { createIndexes: "campaigns", indexes: [ { name: "offers.product_name_1", key: { offers.product_name: 1 }, unique: true, background: false, sparse: false, dropDups: false } ] }

mongo 日志中出现同样的错误:

2015-03-05T13:43:33.696+0000 [conn14] Unauthorized not authorized on campaigns to execute command { createIndexes: "campaigns", indexes: [ { name: "offers.product_name_1", key: { offers.product_name: 1 }, unique: true, background: false, sparse: false, dropDups: false } ] }

您知道发生了什么吗?为什么我的具有读写角色的用户不能执行简单的 findAll,为什么我不能写索引? (以及为什么我们需要编写索引来进行简单的查找查询?)

我在 pymongo 的 bugtracker 上发帖后发现了问题。

我使用的版本不是最新的,但最糟糕的是,mongoengine 没有正确地向 db 进行身份验证。 不要像我一样在连接时进行身份验证,而是做这样的事情:

db = connect("magic", "alias", host="my.url.com", port=port)
db["magic"].authenticate("user", password="pwd")

您可以尝试在 url 中提供此信息,但我认为 mongoengine 会严重使用它们。

谢谢你所做的一切。

我认为这是 mongoengine connect auth 的一个错误。它似乎通过

解决了它
client = connect(<db_name>, host='mongodb://<host1>:<port 1>,<host 2>:<port 2>/<db name>', username="<username>", password="<password>", authentication_source="<auth db name>", replicaSet="<rs name>" )
client.admin.authenticate("<username>", "<password>")

最好解释一下为什么这会解决问题。

如果这对某人有帮助:

这是您尝试对 mongo 数据库执行的第一个操作吗? 也许您的 username/password 配置不正确?使用 mongo,如果您未正确验证,则无需验证即可连接,并且在执行需要验证的操作之前不会出现错误。