Add accessors for bson.D

This commit is contained in:
George Suntres
2026-04-17 20:41:21 -04:00
parent 7a6c5b6c3c
commit f52793a764
2 changed files with 34 additions and 1 deletions

View File

@@ -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 {