Search code examples
mongodbgodriver

How to connect to a mlab mongodb database in go(lang)?


I have a mlab MongoDB database called storyfactory. This database has a collection called test, which has a user called Standard with a Password.

I'm trying to connect to the database with this Driver.
This is the code:

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)
}


If I try to run this code, I get following output:

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

I'm 100% sure that the Password is correct.
Thanks for your help!


Solution

  • Kind of late to the game, but the documentation has all the answers.

    https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo?tab=doc#example-Connect-SCRAM

    Basically, you shouldn't pass your username and password into the connection URI but rather set them as options (see full example below)

    // 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
    

    I've had so many "issues" with this driver, and they were all fixable after I decided to really look at the docs.

    Happy hacking!