You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.5 KiB
60 lines
1.5 KiB
5 years ago
|
package database
|
||
6 years ago
|
|
||
|
import (
|
||
5 years ago
|
"fmt"
|
||
6 years ago
|
"reflect"
|
||
|
|
||
5 years ago
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
|
||
5 years ago
|
"github.com/mainnika/mongox-go-driver/v2/mongox/base"
|
||
6 years ago
|
)
|
||
|
|
||
|
// DeleteArray removes documents list from a database by their ids
|
||
5 years ago
|
func (d *Database) DeleteArray(target interface{}) error {
|
||
6 years ago
|
|
||
|
targetV := reflect.ValueOf(target)
|
||
|
targetT := targetV.Type()
|
||
|
|
||
|
targetK := targetV.Kind()
|
||
|
if targetK != reflect.Ptr {
|
||
5 years ago
|
panic(fmt.Errorf("target is not a ptr"))
|
||
6 years ago
|
}
|
||
|
|
||
|
targetSliceV := targetV.Elem()
|
||
|
targetSliceT := targetT.Elem()
|
||
|
if targetSliceT.Kind() != reflect.Slice {
|
||
5 years ago
|
panic(fmt.Errorf("target should be a ptr to a slice"))
|
||
6 years ago
|
}
|
||
|
|
||
|
targetSliceElemT := targetSliceT.Elem()
|
||
|
if targetSliceElemT.Kind() != reflect.Ptr {
|
||
5 years ago
|
panic(fmt.Errorf("target slice should contain ptrs"))
|
||
6 years ago
|
}
|
||
|
|
||
|
zeroElem := reflect.Zero(targetSliceElemT)
|
||
|
targetLen := targetSliceV.Len()
|
||
5 years ago
|
collection := d.GetCollectionOf(zeroElem.Interface())
|
||
6 years ago
|
opts := options.Delete()
|
||
|
ids := primitive.A{}
|
||
|
|
||
|
for i := 0; i < targetLen; i++ {
|
||
|
elem := targetSliceV.Index(i)
|
||
|
ids = append(ids, base.GetID(elem.Interface()))
|
||
|
}
|
||
|
|
||
|
if len(ids) == 0 {
|
||
5 years ago
|
return fmt.Errorf("can't delete zero elements")
|
||
6 years ago
|
}
|
||
|
|
||
5 years ago
|
result, err := collection.DeleteMany(d.Context(), primitive.M{"_id": primitive.M{"$in": ids}}, opts)
|
||
6 years ago
|
if err != nil {
|
||
5 years ago
|
return fmt.Errorf("can't create find and delete result: %w", err)
|
||
6 years ago
|
}
|
||
|
if result.DeletedCount != int64(targetLen) {
|
||
5 years ago
|
return fmt.Errorf("can't verify delete result: removed count mismatch %d != %d", result.DeletedCount, targetLen)
|
||
6 years ago
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|