dtttlua7165 2015-10-18 23:53
浏览 287

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

I am trying to connect to remote mongodb server in golang and adding data in database. Its giving me error as follows: server returned error on 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.

  • 写回答

2条回答 默认 最新

  • doubiao7410 2015-10-19 02:38
    关注

    You need to call .Login(user, pass string) on the database you need to authenticate with:

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

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

    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害