Connection to remote mongodb server failed in golang giving authentication error

I am trying to connect to a remote mongodb server in golang and add data to the database. This gives me an error: the server responded in the SASL authentication step: Authentication failed.

code:

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

Any help on this is appreciated.

+5
source share
2 answers

You need to call . Entrance (user, transfer string) to the database, which must be performed using:

 if err:= session.DB(authDB).Login(user, pass); err != nil { panic(err) } 

Note that this authenticates the session , so every other session is you . Copy () or . Clone () from it is also authenticated.

+4
source

I was getting a similar error, but found that I entered the wrong credentials.

This code worked for me:

 package main import ( "fmt" "time" "gopkg.in/mgo.v2" ) //const MongoDb details const ( hosts = "ds026491.mongolab.com:26491" database = "messagingdb" username = "admin" password = "youPassword" collection = "messages" ) func main() { info := &mgo.DialInfo{ Addrs: []string{hosts}, Timeout: 60 * time.Second, Database: database, Username: username, Password: password, } session, err1 := mgo.DialWithInfo(info) if err1 != nil { panic(err1) } col := session.DB(database).C(collection) count, err2 := col.Count() if err2 != nil { panic(err2) } fmt.Println(fmt.Sprintf("Messages count: %d", count)) } 

It is also on github

+4
source

Source: https://habr.com/ru/post/1233984/


All Articles