加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 19:28:51 所属栏目:大数据 来源:网络整理
导读:我想在golang中连接到远程 mongodb服务器并在数据库中添加数据.它给我的错误如下: SASL身份验证步骤中服务器返回错误:身份验证失败. 码: package mainimport ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "log" // "os")type Person struct { Name
我想在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)

}

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

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

这段代码对我有用:

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

它也是在Github

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读