Golang中MongoDB插入命令出现未授权错误如何解决
Golang中MongoDB插入命令出现未授权错误如何解决 团队,大家好:
我一直在尝试在 AWS EC2 实例上运行我的项目。我有一个 Ubuntu 实例,在这个实例上,我尝试使用 MongoDB 作为数据库,但是一旦我向其中插入文档,就会显示错误。这个错误不是在我本地个人系统上出现的,而是在这个 Ubuntu 实例上出现的。不过,连接是成功建立的。
我使用了官方的 MongoDB 驱动。
“我的连接字符串。”
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
“错误:”
The error :(Unauthorized) command insert requires authentication
2020/03/12 16:08:40 HTTP: panic serving 210.212.85.151:51744: runtime error: invalid memory
address or nil pointer dereference
请帮我解决这个问题。
更多关于Golang中MongoDB插入命令出现未授权错误如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html
嗨,@vashish,我手头没有足够的信息来亲自测试以确定错误的原因,但根据“(Unauthorized) …”错误下方的“…nil pointer dereference”消息,我建议你检查执行插入操作的代码中是否存在 nil 指针。
// 检查代码中是否存在 nil 指针
更多关于Golang中MongoDB插入命令出现未授权错误如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在MongoDB中遇到"command insert requires authentication"错误,通常是因为连接字符串中缺少认证信息或认证配置不正确。以下是几种解决方案:
1. 在连接字符串中包含认证信息
// 包含用户名、密码和认证数据库
uri := "mongodb://username:password@localhost:27017/admin?authSource=admin"
clientOptions := options.Client().ApplyURI(uri)
2. 使用认证选项单独配置
credential := options.Credential{
Username: "yourUsername",
Password: "yourPassword",
AuthSource: "admin", // 认证数据库,通常是admin
}
clientOptions := options.Client().
ApplyURI("mongodb://localhost:27017").
SetAuth(credential)
3. 检查MongoDB服务配置
确保MongoDB服务已启用认证:
# 连接到MongoDB
mongo
# 在MongoDB shell中创建用户
use admin
db.createUser({
user: "myUser",
pwd: "myPassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
# 重启MongoDB启用认证
sudo systemctl restart mongod
4. 完整的连接示例
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// 方法1:使用连接字符串包含认证
uri := "mongodb://myUser:myPassword@localhost:27017/myDatabase?authSource=admin"
// 方法2:或使用认证选项
clientOptions := options.Client().
ApplyURI("mongodb://localhost:27017").
SetAuth(options.Credential{
Username: "myUser",
Password: "myPassword",
AuthSource: "admin",
})
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
log.Fatal(err)
}
}()
// 测试连接
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
// 插入文档示例
collection := client.Database("myDatabase").Collection("myCollection")
doc := bson.D{{"name", "test"}, {"value", 123}}
insertResult, err := collection.InsertOne(ctx, doc)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Inserted document with ID: %v\n", insertResult.InsertedID)
}
5. 检查用户权限
确保用户对目标数据库有写入权限:
// 在MongoDB shell中授予权限
use myDatabase
db.grantRolesToUser("myUser", [
{ role: "readWrite", db: "myDatabase" }
])
6. 检查连接参数
// 添加连接参数确保稳定性
uri := "mongodb://username:password@localhost:27017/myDatabase?" +
"authSource=admin&" +
"readPreference=primary&" +
"directConnection=true&" +
"ssl=false"
clientOptions := options.Client().
ApplyURI(uri).
SetServerSelectionTimeout(5 * time.Second).
SetConnectTimeout(10 * time.Second)
nil指针解引用错误通常是因为认证失败导致client对象为nil。确保先处理认证错误,再进行数据库操作。

