如何使用Golang和MongoDriver解决"command find requires authentication"问题



我需要帮助来修复错误。我使用的是IBM mongo服务。

go版本go1.13.6达尔文/amd64

mongo驱动程序1.2.1版连接正常,我可以读写,但有时会返回:命令查找需要身份验证指令插入需要身份验证

MONGO_DB_URI=mongodb://username:password:port,host/dbname?authSource=admin&replicaSet=replset&connect=direct&alias=default

连接:

func ConnectDatabase() *mongo.Client {
clientOptions := options.Client().ApplyURI(os.Getenv("MONGO_DB_URI"))
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
var err error
client, err = mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
return nil
}
fmt.Println("Connected to MongoDB!")
return client
}

读取:

func FindAll(collectionName string, query bson.M) (*mongo.Cursor, error) {
collection := client.Database("dbname").Collection(collectionName)
singleResult, err := collection.Find(context.TODO(), query)
return singleResult, err
}

读取:

ctx, _ := context.WithTimeout(context.Background(), 20*time.Second)
cur, err := mongo.GetCollection("collection_name").Find(ctx, createQuery())
if err != nil {
log.Println(err.Error())
}

我在另一个Python项目中使用相同的数据库和相同的配置。没有例外。

连接到数据库和在数据库上执行操作是有区别的。Mongo允许您在没有身份验证的情况下进行连接,因为您必须能够连接才能进行身份验证。

var cred options.Credential
cred.AuthSource = YourAuthSource
cred.Username = YourUserName
cred.Password = YourPassword
// set client options
clientOptions := options.Client().ApplyURI(os.Getenv("MONGO_DB_URI")).SetAuth(cred)
//... the rest of your code

希望这能有所帮助。

最新更新