-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
36 lines (27 loc) · 853 Bytes
/
Copy pathclient.go
File metadata and controls
36 lines (27 loc) · 853 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package mongoclient
import (
"context"
"strings"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring"
)
// Connect returns a new instance of the Mongo database client.
func Connect(ctx context.Context, uri string, databaseName string) (*mongo.Database, error) {
opts := options.Client().ApplyURI(uri)
// Configure the MongoDB API version.
if strings.Contains(uri, connstring.SchemeMongoDBSRV) {
opts.SetServerAPIOptions(options.ServerAPI(options.ServerAPIVersion1))
}
// Create and initialize the MongoDB client.
client, err := mongo.Connect(opts)
if err != nil {
return nil, err
}
// Check the MongoDB client connection.
err = client.Ping(ctx, nil)
if err != nil {
return nil, err
}
return client.Database(databaseName), nil
}