-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete_many.go
54 lines (42 loc) · 1.37 KB
/
delete_many.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
package mgorepo
import (
"context"
"go.mongodb.org/mongo-driver/bson"
)
// DeleteMany deletes many documents from the collection. It returns the number of deleted documents and an error.
// If the repository has timestamps enabled, it will soft delete the documents. Otherwise, it will hard delete them.
func (r Repository[M, D, SF, SORD, SO, UF]) DeleteMany(ctx context.Context, filters SF) (int64, error) {
if !r.withTimestamps {
return r.HardDeleteMany(ctx, filters)
}
bf, err := r.deleteManyFilters(filters)
if err != nil {
return 0, err
}
now := r.Now()
data := bson.M{
"$set": bson.M{
r.updatedAtField: now,
r.deletedAtField: now,
},
}
r.logDebugf(actionDeleteMany, "filters: %+v data: %+v", bf, data)
res, err := r.Collection().UpdateMany(ctx, bf, data)
if err != nil {
r.logErrorf(err, actionDeleteMany, "error deleting %s documents", r.collectionName)
return 0, err
}
return res.ModifiedCount, nil
}
func (r Repository[M, D, SF, SORD, SO, UF]) deleteManyFilters(filters SF) (bson.D, error) {
if r.IsSearchFiltersEmpty(filters) {
r.logErrorf(ErrEmptyFilters, actionDeleteMany, "error deleting many %s document", r.collectionName)
return nil, ErrEmptyFilters
}
bf, err := r.BuildSearchFilters(filters)
if err != nil {
r.logErrorf(err, actionDeleteMany, "error deleting many %s document", r.collectionName)
return nil, err
}
return bf, nil
}