温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How to connect to a mlab mongodb database in go(lang)?
driver go mongodb

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

发布于 2020-05-12 23:57:58

我有一个名为storyfactory的mlab MongoDB数据库。该数据库具有一个名为test的集合,该集合具有一个名为Standard with 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%确保密码正确。
谢谢你的帮助!

查看更多

提问者
Tobi696
被浏览
72
Adrian Oprea 2020-02-24 15:45

有点晚了,但是文档提供了所有答案。

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

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

骇客入侵!