MCPcopy Create free account
hub / github.com/codealong-dev/ride-sharing / NewMongoClient

Function NewMongoClient

shared/db/mongodb.go:35–57  ·  view source on GitHub ↗

NewMongoClient creates a new MongoDB client

(ctx context.Context, cfg *MongoConfig)

Source from the content-addressed store, hash-verified

33
34// NewMongoClient creates a new MongoDB client
35func 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
60func GetDatabase(client *mongo.Client, cfg *MongoConfig) *mongo.Database {

Callers 1

mainFunction · 0.92

Calls

no outgoing calls

Tested by

no test coverage detected