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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度