Golang 和 MongoDb 远程访问失败(服务器在 SASL 身份验证步骤上返回错误:身份验证失败。)

Golang and MongoDb remote access fail (server returned error on SASL authentication step: Authentication failed.)

我正在尝试使用 mgo 库从 Go 连接到远程 MongoDB 数据库 (Mongolab),但出现错误 panic: server returned error on SASL authentication step: Authentication failed。这是我的代码

package main

import (
    "fmt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "log"
)

type Person struct {
    Name  string
    Phone string
}

func main() {
    session, err := mgo.Dial("mongodb://<dbusername>:<dbpassword>@ds055855.mlab.com:55855")

    if err != nil {
        panic(err)
    }
    defer session.Close()

    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("catalog").C("History")
    err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
        &Person{"Cla", "+55 53 8402 8510"})
    if err != nil {
        log.Fatal(err)
    }

    result := Person{}
    err = c.Find(bson.M{"name": "Ale"}).One(&result)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Phone:", result.Phone)
}

我该如何解决这个问题?当然,我没有在代码中添加星标,而是写了我的登录名和密码。

请检查您是否为您的 Mongolab 数据库实例添加了用户(https://mongolab.com/databases/catalog#users 如果您的数据库名称是 catalog),因为默认情况下您的用户列表是空的(帐户 user/password != 数据库 user/password).

同时将 /<databasename> 添加到连接字符串的末尾 - mongodb://*******:*******@ds045795.mongolab.com:45795/databasename.