Add accessors for bson.D
This commit is contained in:
31
struct.go
31
struct.go
@@ -132,6 +132,37 @@ func StructToMapRecursive(obj any) any {
|
||||
}
|
||||
}
|
||||
|
||||
func BsonDGetAny(d bson.D, key string) (any, bool) {
|
||||
for _, e := range d {
|
||||
if e.Key == key {
|
||||
return e.Value, true
|
||||
}
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func BsonDGet[T any](d bson.D, key string) (T, bool) {
|
||||
var zero T
|
||||
|
||||
for _, e := range d {
|
||||
if e.Key == key {
|
||||
val, ok := e.Value.(T)
|
||||
if !ok {
|
||||
return zero, false
|
||||
}
|
||||
|
||||
return val, true
|
||||
}
|
||||
}
|
||||
|
||||
return zero, false
|
||||
}
|
||||
|
||||
func BsonDGetString(d bson.D, key string) (string, bool) {
|
||||
return BsonDGet[string](d, key)
|
||||
}
|
||||
|
||||
func BsonToStruct(m bson.M, o any) error {
|
||||
b, err := bson.Marshal(m)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user