/
activity.go
52 lines (43 loc) · 1008 Bytes
/
activity.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
package migrations
import (
"context"
"github.com/dailytravel/x/insight/graph/model"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type Activity struct {
Database *mongo.Database
Model *model.Activity
}
// Create mongo collection
func (m *Activity) Migrate() error {
col := m.Database.Collection(m.Model.Collection())
indexes, err := col.Indexes().List(context.Background())
if err != nil {
return err
}
indexNames := make(map[string]bool)
for indexes.Next(context.Background()) {
var index bson.M
if err := indexes.Decode(&index); err != nil {
return err
}
indexNames[index["name"].(string)] = true
}
for _, index := range m.Model.Index() {
keys := index.Keys
if keys != nil {
indexName := ""
for _, key := range keys.(bson.D) {
indexName = key.Key
break
}
if !indexNames[indexName] {
if _, err := col.Indexes().CreateOne(context.Background(), index); err != nil {
return err
}
}
}
}
return nil
}