@@ -1569,6 +1569,18 @@ func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr bsonr
1569
1569
return ValueDecoderError {Name : "UnmarshalerDecodeValue" , Types : []reflect.Type {tUnmarshaler }, Received : val }
1570
1570
}
1571
1571
1572
+ // If BSON value is null and the go value is a pointer, then don't call
1573
+ // UnmarshalBSONValue. Even if the Go pointer is already initialized (i.e.,
1574
+ // non-nil), encountering null in BSON will result in the pointer being
1575
+ // directly set to nil here. Since the pointer is being replaced with nil,
1576
+ // there is no opportunity (or reason) for the custom UnmarshalBSONValue logic
1577
+ // to be called.
1578
+ if val .Kind () == reflect .Ptr && vr .Type () == bsontype .Null {
1579
+ val .Set (reflect .Zero (val .Type ()))
1580
+
1581
+ return vr .ReadNull ()
1582
+ }
1583
+
1572
1584
if val .Kind () == reflect .Ptr && val .IsNil () {
1573
1585
if ! val .CanSet () {
1574
1586
return ValueDecoderError {Name : "UnmarshalerDecodeValue" , Types : []reflect.Type {tUnmarshaler }, Received : val }
@@ -1581,18 +1593,6 @@ func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr bsonr
1581
1593
return err
1582
1594
}
1583
1595
1584
- // If the target Go value is a pointer and the BSON field value is empty, set the value to the
1585
- // zero value of the pointer (nil) and don't call UnmarshalBSON. UnmarshalBSON has no way to
1586
- // change the pointer value from within the function (only the value at the pointer address),
1587
- // so it can't set the pointer to "nil" itself. Since the most common Go value for an empty BSON
1588
- // field value is "nil", we set "nil" here and don't call UnmarshalBSON. This behavior matches
1589
- // the behavior of the Go "encoding/json" unmarshaler when the target Go value is a pointer and
1590
- // the JSON field value is "null".
1591
- if val .Kind () == reflect .Ptr && len (src ) == 0 {
1592
- val .Set (reflect .Zero (val .Type ()))
1593
- return nil
1594
- }
1595
-
1596
1596
if ! val .Type ().Implements (tUnmarshaler ) {
1597
1597
if ! val .CanAddr () {
1598
1598
return ValueDecoderError {Name : "UnmarshalerDecodeValue" , Types : []reflect.Type {tUnmarshaler }, Received : val }
0 commit comments