NewMongoClient creates a new MongoDB client
(ctx context.Context, cfg *MongoConfig)
| 33 | |
| 34 | // NewMongoClient creates a new MongoDB client |
| 35 | func NewMongoClient(ctx context.Context, cfg *MongoConfig) (*mongo.Client, error) { |
| 36 | if cfg.URI == "" { |
| 37 | return nil, fmt.Errorf("mongodb URI is required") |
| 38 | } |
| 39 | if cfg.Database == "" { |
| 40 | return nil, fmt.Errorf("mongodb database is required") |
| 41 | } |
| 42 | |
| 43 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| 44 | defer cancel() |
| 45 | client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.URI)) |
| 46 | if err != nil { |
| 47 | return nil, err |
| 48 | } |
| 49 | |
| 50 | err = client.Ping(ctx, readpref.Primary()) |
| 51 | if err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 | |
| 55 | log.Printf("Successfully connected to MongoDB at %s", cfg.URI) |
| 56 | return client, nil |
| 57 | } |
| 58 | |
| 59 | // GetDatabase returns a database instance |
| 60 | func GetDatabase(client *mongo.Client, cfg *MongoConfig) *mongo.Database { |