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 (

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)
        _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.


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doufei3152 doufei3152 5年前

    Found the problem

    I was importing the wrong go module.

    I had:

    instead of:

    After importing it made the connection

    点赞 评论 复制链接分享