猿问

如何在 go(lang) 中连接到 mlab mongodb 数据库?

我有一个名为 storyfactory 的 mlab MongoDB 数据库。该数据库有一个名为 test 的集合,其中有一个名为 Standard 的用户和密码。 我正在尝试使用此Driver

连接到数据库。 这是代码:

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() {

    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)

    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://<Standard>:<Password>@ds127101.mlab.com:27101/storyfactory"))

    if err != nil {

        log.Fatal(err)

    }

    collection := client.Database("storyfactory").Collection("test")

    ctx, _ = context.WithTimeout(context.Background(), 5*time.Second)

    res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})

    if err != nil {

        log.Fatal(err)

    }

    fmt.Println(res.InsertedID)

}


如果我尝试运行这段代码,我会得到以下输出:


2019/03/12 18:09:04 auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.

exit status 1

我 100% 确定密码是正确的。

感谢您的帮助!


扬帆大鱼
浏览 130回答 1
1回答

白猪掌柜的

有点晚了,但文档有所有答案。https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo?tab=doc#example-Connect-SCRAM基本上,您不应该将您的用户名和密码传递到连接 URI 中,而是将它们设置为选项(参见下面的完整示例)// Configure a Client with SCRAM authentication (https://docs.mongodb.com/manual/core/security-scram/).// The default authentication database for SCRAM is "admin". This can be configured via the// authSource query parameter in the URI or the AuthSource field in the options.Credential struct.// SCRAM is the default auth mechanism so specifying a mechanism is not required.// To configure auth via URI instead of a Credential, use// "mongodb://user:password@localhost:27017".credential := options.Credential{&nbsp; &nbsp; Username: "user",&nbsp; &nbsp; Password: "password",}clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential)client, err := mongo.Connect(context.TODO(), clientOpts)if err != nil {&nbsp; &nbsp; log.Fatal(err)}_ = client这个驱动程序有很多“问题”,在我决定真正查看文档后,它们都是可以解决的。
随时随地看视频慕课网APP

相关分类

Go
我要回答