/
create_indexes.go
44 lines (35 loc) · 1.04 KB
/
create_indexes.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
package xmongo
import (
"context"
"github.com/AltScore/gothic/pkg/xlogger"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.uber.org/zap"
)
// CreateIndexes creates one or more indexes in the provided collection reporting the result in the log
func CreateIndexes(logger xlogger.Logger, collection *mongo.Collection, models ...mongo.IndexModel) {
var cancel context.CancelFunc
defer func() {
if cancel != nil {
cancel()
}
}()
for _, model := range models {
var ctx context.Context
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
indexName, err := collection.Indexes().CreateOne(ctx, model)
if err != nil {
fields := []zap.Field{
zap.String("collection", collection.Name()),
zap.Error(err),
}
if model.Options.Name != nil {
fields = append(fields, zap.String("index", *model.Options.Name))
}
logger.Warn("Failed to create index", fields...)
} else {
logger.Info("Created index", zap.String("collection", collection.Name()), zap.String("index", indexName))
}
cancel()
}
}