[GODRIVER-317] Handle nil properties of a struct in the BSON encoder Created: 27/Mar/18  Updated: 01/Oct/18  Resolved: 05/Apr/18

Status: Closed
Project: Go Driver
Component/s: None
Affects Version/s: 0.0.2
Fix Version/s: 0.0.3

Type: Improvement Priority: Major - P3
Reporter: Kristofer Brandow (Inactive) Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
is depended on by GODRIVER-315 Mongo shipped BSON marshaller to supp... Closed
Duplicate
is duplicated by GODRIVER-315 Mongo shipped BSON marshaller to supp... Closed
Epic Link: GODRIVER Alpha UX

 Description   

The BSON encoder does not handle struct properties that can be nil. If it does encounter a nil struct property it returns an error when it should encode that value into a BSON Null.

To fix this:

  • Update underlyingVal to check if the value is nil when it's Kind is either a reflect.Ptr or a reflect.Interface. If it is, don't return the underlying Elem, instead return the pointer or interface.
  • In encodeMap, encodeSlice, encodeSliceAsArray, and encodeStruct, after calling underlyingVal, if the kind is an interface, map, pointer, or slice, and it is nil, return a BSON Null type.


 Comments   
Comment by Travis Terry [ 01/Oct/18 ]

This is still an issue with the StructCodec when trying to encode a struct that has a field which is a pointer to another struct. If the pointer is nil, it fails to encode here https://github.com/mongodb/mongo-go-driver/blob/master/bson/bsoncodec/struct_codec.go#L50. That needs a val.IsNil() check.

Also, it took me a long time to track this down. I see that you return an error that the encoder "can only process structs," but that error is later replaced by a more generic error "failed to encode." Returning the more specific error would have made this a lot easier to find.

 

 

Comment by Githook User [ 05/Apr/18 ]

Author:

{'email': 'kris@mongodb.com', 'name': 'Kris Brandow', 'username': 'skriptble'}

Message: Handle nil properly in BSON encoder

Added support for nil interfaces, maps, pointers, and slices.
Added support for round tripping empty maps and slices and nil maps and
slices. Since these are distinct in Go, we use BSON Null for a nil map
or slice and an empty document or array, respectively, for zero value
map and slice types.

GODRIVER-317
GODRIVER-315

Change-Id: I96036138acb745b1f42d3190e9664366bb85a9a6
Branch: master
https://github.com/mongodb/mongo-go-driver/commit/bf482478e9fde8a815ce22eec54a36c0ab410502

Comment by Kristofer Brandow (Inactive) [ 03/Apr/18 ]

Code Review: https://review.gerrithub.io/c/406250/.

Comment by Kristofer Brandow (Inactive) [ 27/Mar/18 ]

This bug will cause problems with some of our internal types that use pointers if we ever try to marshal them, so scheduling this.

Generated at Thu Feb 08 08:33:57 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.