繁体   English   中英

如何使用 Golang 和 MongoDriver 解决“命令查找需要身份验证”

[英]How to solve "command find requires authentication" using Golang and MongoDriver

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

转到版本 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 项目中使用相同的数据库和相同的配置。 没有例外。

连接到 DB 和在 DB 上执行操作之间存在差异。 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

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM