/
mongodb.go
59 lines (45 loc) · 1.29 KB
/
mongodb.go
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package mongodb
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var db *mongo.Database
func Connect(uri, dbName string) {
var (
ctx = context.Background()
)
// use the SetServerAPIOptions() method to set the Stable API version to 1
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI)
client, err := mongo.Connect(ctx, opts)
if err != nil {
panic(err)
}
// send a ping to confirm a successful connection
if err = client.Database("admin").RunCommand(ctx, bson.M{"ping": 1}).Err(); err != nil {
panic(err)
}
fmt.Printf("⚡️ [mongodb]: connected \n")
db = client.Database(dbName)
// index
go colIndexes()
}
func UserCol() *mongo.Collection {
return db.Collection(collectionNames.User)
}
func MonitorCol() *mongo.Collection {
return db.Collection(collectionNames.Monitor)
}
func HealthCheckRecordCol() *mongo.Collection {
return db.Collection(collectionNames.HealthCheckRecord)
}
func NewObjectID() primitive.ObjectID {
return primitive.NewObjectID()
}
func ObjectIDFromString(id string) (primitive.ObjectID, error) {
return primitive.ObjectIDFromHex(id)
}