MongoDB - 命令执行失败,错误代码为13,`未被*****授权执行此命令`。

13

因为某种奇怪的原因,我的用户没有被授权在krimson数据库中写入任何内容。数据库连接成功,但是授予用户写入数据库的权限并未按预期工作。

完整错误信息

Caused by: com.mongodb.MongoCommandException: Command failed with error 13: 'not authorized on krimson to execute command { findandmodify: "users", query: { _id: "_id" }, fields: {}, sort: {}, new: true, upsert: true, update: { $i
nc: { _id: 1 } } }' on server ds037395.mongolab.com:37395. The full response is { "ok" : 0.0, "errmsg" : "not authorized on krimson to execute command { findandmodify: \"users\", query: { _id: \"_id\" }, fields: {}, sort: {}, new:
 true, upsert: true, update: { $inc: { _id: 1 } } }", "code" : 13 }

连接代码

    public static void connects(String ip, int port, String database, String username, String password) {
    try {
        client = new MongoClient(ip, port); /**Creating our connection between server & MongoDB*/
        krimson = client.getDB(database); /**Checks if the database exists or not if not then create a new one*/

        MongoCredential.createCredential(username, database, password.toCharArray()); /**Credentials used to connect to MongoDB*/

    } catch (Exception e){
        e.printStackTrace();
        System.out.println("Linking connections failed"); /**Outputs when the database cannot connect*/
        UtilServer.broadcast("&c&lThe Krimson Library did not establish a successfully connection.");
    }

    users = krimson.getCollection("users");

}

我已尝试重新创建用户并修复凭据,以查看是否存在问题,但事实并非如此。目前我正在使用MongoLab。因此,我想知道这可能是问题之一还是其他原因,或者在MongoLab中手动分配用户管理员角色是否需要特定的方法。

3个回答

4

您需要在mongo shell中授予用户帐户写入权限:

use krimson
db.grantRolesToUser(
    "reportsUser",
    [
      { role: "write", db: "krimson" }
    ]
 )

我完全不懂MongoDB,我应该把这个放在哪里或者怎样执行它? - Crypt Junior
@Messa 那我需要连接Mongo Shell并执行命令吗?我正在使用MongoLab? - Crypt Junior
你可以运行 mongo ds037395.mongolab.com:37395 - Alex
1
和@CryptJunior犯了同样的错误,但授予这个角色并没有解决问题。 - Fernando M. Pinheiro
抱歉再次留言,但有人成功解决了这个问题吗?我这里也遇到了同样奇怪的问题 :-( - Cotta
此外,我已经抓狂了两天。在我的情况下,我正在使用Spring Boot 2.1.1与响应式MongoDB。如果有人解决了这个问题,请帮忙。 - uday214125

4

我遇到了相同的错误。

所以我尝试了下面的代码,对我起作用。

MongoCredential credential = MongoCredential.createCredential("xyz", "admin", "password".toCharArray());
        MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 1235), Arrays.asList(credential));

2

我遇到了同样的错误,并通过设置authSource=admin来解决它。

示例URL字符串

mongodb://root:example@localhost:27017/learningdb?authSource=admin&retryWrites=true&w=majority

用户已经具有完全的权限,并且Spring Boot在启动时能够连接到MongoDB。问题出现在访问来自Mongo存储库的数据时,它无法验证用户身份。提供authSource解决了这个问题。


"root:example" 代表什么? - Lutosław
在我的情况下,我只需用我的用户名和密码替换“root:example”。 - M E S A B O

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接