Home > front end >  Create role for mongo
Create role for mongo

Time:02-22

In Go, I am adding a user to mongo and want to create a role, which grants access only to a specific collection. I am new to mongo, so not sure exactly how to do this. My attempt is to use the RunCommand. Below is what I tried, but I am getting a:
runtime error: invalid memory address or nil pointer dereference

Below my code, I verified that the values for database and id are properly set.

createRoleResult := client.Database(db).RunCommand(ctx, bson.D{{"createRole", id},
        {"privileges", []bson.M{
            {
                "resource": bson.A{bson.M{"db": db}, bson.M{"collection": id}, bson.M{"actions": bson.A{"update", "insert", "remove"}}},
            },
    }}})

This code results in the same:

    createRoleResult := client.Database(db).RunCommand(ctx, bson.D{{"createRole", id},
        {"privileges", []bson.A{
            {
                bson.D{bson.E{"resource", bson.A{bson.D{bson.E{"db", db}}, bson.D{bson.E{"collection", id}}, bson.E{"actions", bson.A{"update", "insert", "remove"}}}}},
            },
        }}})

Any advice would be appreciated! If there are better approaches to this, I'm all ears.

Working shell code:

db.createRole(
   {
     role: "ABC",
     privileges: [
       { resource: { db: "MyDB", collection: "ABC" }, actions: [ "update", "insert", "remove", "find" ] }
     ],
     roles: []
   }
)

Thanks!

CodePudding user response:

You can try this Golang code:

var commandResult bson.M
command := bson.D{{ "createRole", "ABC" }, { "privileges", bson.A{ bson.D{{ "resource", bson.D{{ "db", "MyDB" }, { "collection", "ABC" }}}, { "actions", bson.A{ "update", "insert" }}}}}, { "roles", bson.A{}}}
err = client.Database("test").RunCommand(context.TODO(), command).Decode(&commandResult)

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

fmt.Println(commandResult)
  • Related