【问题标题】:How to connect to a mlab mongodb database in go(lang)?如何在 go(lang) 中连接到 mlab mongodb 数据库?
【发布时间】:2019-08-03 06:13:57
【问题描述】:

我有一个名为 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% 确定密码正确。
感谢您的帮助!

【问题讨论】:

  • 如果您将相同的凭据复制并粘贴到mongo -u -p 中是否有效?随着错误的发生,“身份验证失败”很难争辩。
  • 尝试联系 mLab 的支持团队 (support@mlab.com)。他们可以帮助解决这些类型的问题。
  • 您是否尝试指定身份验证机制?像 mongodb://&lt;Standard&gt;:&lt;Password&gt;@ds127101.mlab.com:27101/storyfactory?authMechanism=SCRAM-SHA-1 这样的网址。另外您使用的是哪个版本的 mongo 驱动程序?
  • 我现在删除了我的 mlab 帐户,然后注册了一个新帐户。似乎他们现在正在将所有用户重定向到 mongo 云。但是,我现在使用了一个稍微不同的 URI,但它可以工作!感谢您的努力!
  • 很高兴您现在可以使用它@Tobi696。对于背景信息,mLab 现在是 MongoDB 的一部分。见blog.mlab.com/2018/10/mlab-is-becoming-a-part-of-mongodb-inc

标签: mongodb go driver


【解决方案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{
    Username: "user",
    Password: "password",
}
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetAuth(credential)
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
    log.Fatal(err)
}
_ = client

我对这个驱动程序有很多“问题”,在我决定真正查看文档后,它们都可以解决。

黑客愉快!

【讨论】:

  • 我试过同样的方法。它在终端工作正常。但是在我的代码中仍然出现上面提到的相同错误。
猜你喜欢
  • 1970-01-01
  • 2017-08-27
  • 2019-05-05
  • 2016-07-05
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
相关资源
最近更新 更多