doulan8330 2016-06-25 21:09
浏览 115
已采纳

无法连接Mlab数据库,但是我可以使用mgo golang连接到本地mongo

I am trying to connect to a mlab mongo database in my Golang application but I always get 'auth failed'.

If I use my local mongo, I have no problems (my local doesn't have authentication)

EDIT: I do have created a database user in mLab and I can log in with that user in RoboMongo

My database package looks like this:

package database

import (
    "os"
    "fmt"
    "sync"
    "labix.org/v2/mgo"
    "time"
)

type DB struct {
    Database    *mgo.Database
}


const (
  MongoDBHosts = "mlabHost:mlabPort"
  AuthDatabase = "mydatabase"
  AuthUserName = "mlabUser"
  AuthPassword = "mlabPassword"
)

var _init_ctx sync.Once
var _instance *DB

func New() *mgo.Database {
    _init_ctx.Do(func() {
        _instance = new(DB)

        mongoDBDialInfo := &mgo.DialInfo{
            Addrs:    []string{MongoDBHosts},
            Timeout:  600 * time.Second,
            Database: AuthDatabase,
            Username: AuthUserName,
            Password: AuthPassword,
        }

        // Create a session which maintains a pool of socket connections
        // to our MongoDB.
        session, err := mgo.DialWithInfo(mongoDBDialInfo)

        if err != nil {
            fmt.Printf("Error en mongo: %+v
", err)
            os.Exit(1)
        }
        _instance.Database = session.DB(AuthDatabase)
    })
    return _instance.Database
}

With that code, I always get 'auth failed', but if I change the const values to connect to my local like this:

const (
    MongoDBHosts = "localhost:27017"
    AuthDatabase = "mydatabase"
    AuthUserName = ""
    AuthPassword = ""
)

Everything is good.

I can even connect to my mLab database through RoboMongo, but one thing I noticed was that trying to connect from the command line like this:

mongo mLabHost:mLabPort/mydatabase -u mLabUser -p mLabPassword

The prompt asks again for the password and then I get (mypassword = mLabPassword I enter):

2016-06-25T16:07:10.822-0500 E -        [main] file [mypassword] doesn't exist
failed to load: mypassword

I tried connecting to mLab in several different ways, but I can't find what is my problem.

Thanks

  • 写回答

1条回答 默认 最新

  • doufei3152 2016-06-25 23:28
    关注

    Found the problem

    I was importing the wrong go module.

    I had:

    labix.org/v2/mgo
    

    instead of:

    gopkg.in/mgo.v2
    

    After importing gopkg.in/mgo.v2 it made the connection

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)