-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexes.go
36 lines (31 loc) · 1.08 KB
/
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
package modm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
// EnsureIndexes creates unique and non-unique indexes in the collection.
func (r *Repo[T]) EnsureIndexes(ctx context.Context, uniques []string, indexes []string, indexModels ...mongo.IndexModel) error {
indexesModel := IndexesToModel(uniques, indexes)
indexesModel = append(indexesModel, indexModels...)
var err error
if len(indexesModel) > 0 {
_, err = r.collection.Indexes().CreateMany(ctx, indexesModel)
}
return err
}
// Indexes is an interface for defining unique and non-unique indexes.
type Indexes interface {
Uniques() []string
Indexes() []string
IndexModels() []mongo.IndexModel
}
// EnsureIndexesByModel creates indexes in the collection based on an Indexes interface.
func (r *Repo[T]) EnsureIndexesByModel(ctx context.Context, model Indexes) error {
indexesModel := IndexesToModel(model.Uniques(), model.Indexes())
indexesModel = append(indexesModel, model.IndexModels()...)
var err error
if len(indexesModel) > 0 {
_, err = r.collection.Indexes().CreateMany(ctx, indexesModel)
}
return err
}