Golang mongo-driver: getting `omitempty` struct tag to evaluate golang primitives

Per the documentation:
omitempty: If the omitempty struct tag is specified on a field, the field will not be marshalled if it is set to
the zero value. By default, a struct field is only considered empty if the field’s type implements the Zeroer
interface and the IsZero method returns true. Struct fields of types that do not implement Zeroer are always
marshalled as embedded documents. This tag should be used for all slice and map values.

Since golang primitives don’t implement Zeroer, passing usual zero values (such as bool(false), int(0), string("")) still get encoded into the bson objects.

Is the appropriate path to create a new Registry, registering bsoncodec.DefaultValueEncoders/bsoncodec.DefaultValueDecoders, and then registering my custom Type Encoder for each type I want to implement IsTypeZeroer?

Hi @Brian_McQueen,

Sorry for the late reply. The documentation is implying that fields which are structs will only be considered empty if the type implements Zeroer. Fields with non-struct types like booleans, numbers, maps, slices, and pointers are handled directly by the driver. You can see the code to determine if a field should be considered empty here and an example showing that primitives are automatically handled without any additional code here.

I’ve opened a PR to clarify this documentation.

/crazypills

I could have sworn omitempty tagged zero-value primitives were still being marshalled, but I’m no longer able to reproduce, so I’m clearly way off.

Thanks for the clarification!