猿问

golang 连接到远程 mongodb 服务器失败,出现身份验证错误

我正在尝试连接到 golang 中的远程 mongodb 服务器并在数据库中添加数据。它给了我如下错误:服务器在 SASL 身份验证步骤返回错误:身份验证失败。


代码:


package main


import (

    "fmt"

    "gopkg.in/mgo.v2"

    "gopkg.in/mgo.v2/bson"

    "log"

    // "os"

)


type Person struct {

    Name  string

    Phone string

}


func main() {


    session, err := mgo.Dial("mongodb://<dbuser>:<dbpassword>@ds041154.mongolab.com:41154/location")


    if err != nil {

        fmt.Println(err)

    } else {

        fmt.Println("Session created")

    }


    // Optional. Switch the session to a monotonic behavior.

    session.SetMode(mgo.Monotonic, true)


    c := session.DB("location").C("people")

    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)


}

对此的任何帮助表示赞赏。


智慧大石
浏览 336回答 2
2回答

天涯尽头无女友

我遇到了类似的错误,但我发现我输入了错误的登录凭据。这段代码对我有用:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time"&nbsp; &nbsp; "gopkg.in/mgo.v2")//const MongoDb detailsconst (&nbsp; &nbsp; hosts&nbsp; &nbsp; &nbsp; = "ds026491.mongolab.com:26491"&nbsp; &nbsp; database&nbsp; &nbsp;= "messagingdb"&nbsp; &nbsp; username&nbsp; &nbsp;= "admin"&nbsp; &nbsp; password&nbsp; &nbsp;= "youPassword"&nbsp; &nbsp; collection = "messages")func main() {&nbsp; &nbsp; info := &mgo.DialInfo{&nbsp; &nbsp; &nbsp; &nbsp; Addrs:&nbsp; &nbsp; []string{hosts},&nbsp; &nbsp; &nbsp; &nbsp; Timeout:&nbsp; 60 * time.Second,&nbsp; &nbsp; &nbsp; &nbsp; Database: database,&nbsp; &nbsp; &nbsp; &nbsp; Username: username,&nbsp; &nbsp; &nbsp; &nbsp; Password: password,&nbsp; &nbsp; }&nbsp; &nbsp; session, err1 := mgo.DialWithInfo(info)&nbsp; &nbsp; if err1 != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err1)&nbsp; &nbsp; }&nbsp; &nbsp; col := session.DB(database).C(collection)&nbsp; &nbsp; count, err2 := col.Count()&nbsp; &nbsp; if err2 != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err2)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(fmt.Sprintf("Messages count: %d", count))}

慕标5832272

您需要在需要进行身份验证的数据库上调用.Login(user, pass string):if&nbsp;err:=&nbsp;session.DB(authDB).Login(user,&nbsp;pass);&nbsp;err&nbsp;!=&nbsp;nil&nbsp;{ &nbsp;&nbsp;panic(err) &nbsp;&nbsp;}请注意,这会验证session,因此您从中 .Copy()或.Clone() 的每个其他会话也经过验证。
随时随地看视频慕课网APP

相关分类

Go
我要回答