golang中与远程mongodb服务器的连接失败,导致身份验证错误

前端之家收集整理的这篇文章主要介绍了golang中与远程mongodb服务器的连接失败,导致身份验证错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在golang中连接到远程 mongodb服务器并在数据库添加数据.它给我的错误如下:
SASL身份验证步骤中服务器返回错误:身份验证失败.

码:

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "gopkg.in/mgo.v2"
  6. "gopkg.in/mgo.v2/bson"
  7. "log"
  8. // "os"
  9. )
  10.  
  11. type Person struct {
  12. Name string
  13. Phone string
  14. }
  15.  
  16. func main() {
  17.  
  18. session,err := mgo.Dial("mongodb://<dbuser>:<dbpassword>@ds041154.mongolab.com:41154/location")
  19.  
  20. if err != nil {
  21. fmt.Println(err)
  22. } else {
  23. fmt.Println("Session created")
  24. }
  25.  
  26. // Optional. Switch the session to a monotonic behavior.
  27. session.SetMode(mgo.Monotonic,true)
  28.  
  29. c := session.DB("location").C("people")
  30. err = c.Insert(&Person{"Ale","+55 53 8116 9639"},&Person{"Cla","+55 53 8402 8510"})
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34.  
  35. result := Person{}
  36. err = c.Find(bson.M{"name": "Ale"}).One(&result)
  37. if err != nil {
  38. log.Fatal(err)
  39. }
  40.  
  41. fmt.Println("Phone:",result.Phone)
  42.  
  43. }

对此有任何帮助表示赞赏.

我得到了类似的错误,但我发现我输入了错误登录凭据.

这段代码对我有用:

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "time"
  6.  
  7. "gopkg.in/mgo.v2"
  8. )
  9.  
  10. //const MongoDb details
  11. const (
  12. hosts = "ds026491.mongolab.com:26491"
  13. database = "messagingdb"
  14. username = "admin"
  15. password = "youPassword"
  16. collection = "messages"
  17. )
  18.  
  19. func main() {
  20.  
  21. info := &mgo.DialInfo{
  22. Addrs: []string{hosts},Timeout: 60 * time.Second,Database: database,Username: username,Password: password,}
  23.  
  24. session,err1 := mgo.DialWithInfo(info)
  25. if err1 != nil {
  26. panic(err1)
  27. }
  28.  
  29. col := session.DB(database).C(collection)
  30.  
  31. count,err2 := col.Count()
  32. if err2 != nil {
  33. panic(err2)
  34. }
  35. fmt.Println(fmt.Sprintf("Messages count: %d",count))
  36. }

它也是在Github

猜你在找的Go相关文章