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

问题描述 投票:2回答:1

我有一个名为storyfactory的mlab MongoDB数据库。该数据库具有一个名为test的集合,该集合具有一个名为Standard和Password的用户。我正在尝试使用此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%确定密码正确。感谢您的帮助!

mongodb go driver
1个回答
0
投票

游戏后期,但文档提供了所有答案。

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

我有很多与此驱动程序有关的“问题”,在我决定真正查看文档后,它们都可以修复。

快乐黑客!

© www.soinside.com 2019 - 2024. All rights reserved.