forked from matroskin13/stepper
/
db.go
35 lines (28 loc) · 778 Bytes
/
db.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
package examples
import (
"context"
"os"
"time"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func CreateMongoDatabase(dbName string) (*mongo.Database, error) {
cmdMonitor := &event.CommandMonitor{
Started: func(_ context.Context, evt *event.CommandStartedEvent) {
// log.Print(evt.Command)
},
}
mongoHost := os.Getenv("MONGO_HOST")
if mongoHost == "" {
mongoHost = "mongodb://localhost:27017"
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoHost).SetMonitor(cmdMonitor))
if err != nil {
return nil, err
}
db := mongoClient.Database(dbName)
return db, nil
}