2

I need help to fix the error. I'm using IBM mongo services.

go version go1.13.6 darwin/amd64

mongo driver version 1.2.1 The connection is working, I can read and write but sometimes it returns : command find requires authentication and command insert requires authentication

MONGO_DB_URI=mongodb://username:password:port,host/dbname?authSource=admin&replicaSet=replset&connect=direct&alias=default

Connect:

 func ConnectDatabase() *mongo.Client {
    clientOptions := options.Client().ApplyURI(os.Getenv("MONGO_DB_URI"))

    ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
    var err error
    client, err = mongo.Connect(ctx, clientOptions)

    if err != nil {
        log.Fatal(err)
    }

    ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Ping(ctx, nil)

    if err != nil {
        log.Fatal(err)
        return nil
    }

    fmt.Println("Connected to MongoDB!")
    return client
}

Read:

func FindAll(collectionName string, query bson.M) (*mongo.Cursor, error) {
    collection := client.Database("dbname").Collection(collectionName)
    singleResult, err := collection.Find(context.TODO(), query)
    return singleResult, err
}

Read:

    ctx, _ := context.WithTimeout(context.Background(), 20*time.Second)
    cur, err := mongo.GetCollection("collection_name").Find(ctx, createQuery())
    if err != nil {
        log.Println(err.Error())
    }

I'm using the same database and the same configurations at our another Python Project. No exceptions.

1
  • The problem is mongo connects without any authentication but you cannot perform any operations without proper access. Commented Feb 19, 2020 at 15:44

1 Answer 1

4

There is a difference between connecting to a DB and performing operations on the DB. Mongo lets you connect without authentication because you have to be able to connect to be able to authenticate.

var cred options.Credential

cred.AuthSource = YourAuthSource
cred.Username = YourUserName
cred.Password = YourPassword

// set client options
clientOptions := options.Client().ApplyURI(os.Getenv("MONGO_DB_URI")).SetAuth(cred)

//... the rest of your code

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.