Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run command in MongoDB with go driver

Tags:

mongodb

go

I try to run the createUser command. I think the problem is that the order of the fields plays an important role. The command worked exactly like this. But suddenly I get the following error:

panic: (CommandNotFound) no such command: 'pwd', bad cmd: '{ pwd: "Test123!", roles: [ { role: "readWrite", db: "test" } ], createUser: "test" }'

So without changing anything the function sometimes works and sometimes it doesn't. The following function creates the user:

import (
    "context"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "log"
    "os"
    "solvitaInit/kube"
    "time"
)
func createUser(client *mongo.Client, userName string, pass string, dbName string, roleName string, roldeDB string)  error {
    r := client.Database(dbName).RunCommand(context.Background(),bson.M{"createUser": userName, "pwd": pass,
        "roles": []bson.M{{"role": roleName,"db":roldeDB}}})
    if r.Err() != nil {
        panic(r.Err())
    }
    return nil
}

Is there a way how to force an order. Or am I doing somehting else wrong?

Solution:

r := client.Database(dbName).RunCommand(context.Background(),bson.D{{"createUser", userName},
        {"pwd", pass}, {"roles", []bson.M{{"role": roleName,"db":roldeDB}}}})
    if r.Err() != nil {
        panic(r.Err())
    }
like image 488
SamuelTJackson Avatar asked Mar 05 '26 14:03

SamuelTJackson


2 Answers

godoc says: The runCommand parameter ... must be an order-preserving type such as bson.D. Map types such as bson.M are not valid. ...

Try with bson.A (bson array)

r := client.Database(repoDB).RunCommand(
    context.Background(),
    bson.D{{"createUser", "user1"}, {"pwd", "pass"},
        {"roles", bson.A{bson.D{{"role", "clusterAdmin"}, {"db", "admin"}}, "readWrite"}}},
    )
if r.Err() != nil {
    panic(r.Err())
}

Check for other options in MongoDb docs: https://docs.mongodb.com/manual/reference/command/createUser/

like image 29
Cem Ikta Avatar answered Mar 08 '26 00:03

Cem Ikta