diff --git a/mongo_replica_init.go b/mongo_replica_init.go index e53e28c..7b41778 100644 --- a/mongo_replica_init.go +++ b/mongo_replica_init.go @@ -2,44 +2,43 @@ package main import ( "context" + "time" "fmt" - - "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/bson" ) - func initReplMongo() { - // Create a new client and connect to the servers - client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:30000")) - if err != nil { - panic(err) - } - defer client.Disconnect(context.TODO()) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() - // Get a handle to the admin database - admin := client.Database("admin") + // Create a new replica set client + client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://sasha:12345@localhost:30000/?directConnection=true")) + if err != nil { + panic(err) + } - // Define the replica set configuration - config := bson.M{ - "_id": replicasetName, - "members": []bson.M{}, - } + db := client.Database("admin") - for i := 0; i < int(numberOfContainers); i++ { - member := bson.M{ + members := make([]bson.M, numberOfContainers) + for i := 0; i < numberOfContainers; i++ { + members[i] = bson.M{ "_id": i, "host": fmt.Sprintf("mongo%d", i), } - config["members"] = append(config["members"].([]bson.M), member) } - // Initiate the replica set - res, err := admin.RunCommand(context.TODO(), bson.D{{"replSetInitiate", config}}).Raw() + config := bson.M{ + "_id": replicasetName, + "members": members, + } + + command := bson.D{{"replSetInitiate", config}} + var result bson.M + err = db.RunCommand(context.TODO(), command).Decode(&result) if err != nil { - panic(err) - } - - fmt.Println(res) + panic(err) + } + client.Disconnect(ctx) } \ No newline at end of file