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())
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With