doulan8330
doulan8330
2016-06-25 21:09

无法连接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 doufei3152 5年前

    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

    点赞 评论 复制链接分享