Notice that the v2 code no longer honors the MarshalBSONValue interface and returns a bson.TypeDocument instead of a bson.TypeArray. From some quick inline fmt.Printf’s, it doesn’t look like the MarshalBSONValue function is even being called in v2.
This isn’t mentioned in the release notes as a breaking change that I can find. Is this a bug or is there a new method for achieving the same results as the v1 code?
type ValueMarshaler interface {
MarshalBSONValue() (typ byte, data []byte, err error)
}
In v1, the interface was:
type ValueMarshaler interface {
MarshalBSONValue() (bsontype.Type, []byte, error)
}
The first return value changed from bsontype.Type to byte. The purpose is to allow Go modules to implement the bson.ValueMarshaler interface without depending directly on the Go Driver module.
To fix your v2 example, change the type of the first return value of the MarshalBSONValue methods to byte instead of bson.Type. See an updated version of your code samples here. You can also add a compile-time check to confirm your types implement the bson.ValueMarshaler interface like this:
var _ bson.ValueMarshaler = String{}
var _ bson.ValueMarshaler = StringArray{}
Please let me know if that fixes your issue! By the way, which release notes are you looking at for breaking changes?
I did note the changes in the documentation and the release notes, however, the typ byte threw me due to the bson.MarshalValue call using bson.Type and bsontype.Type being removed and now bson.Type so my brain auto converted to using the same here, which, of course, does not satisfy the interface -
Is there a reason to not use bson.Type in this interface to keep it consistent across the two (and also the ValueUnmarshaler)?
@Mike_71464 I’m glad you were able to fix the issue and sorry about the confusion!
The change in v2 is to allow 3rd-party libraries to implement bson.ValueMarshaler and bson.ValueUnmarshaler without having to depend directly on the Go Driver module. For example, many types in Go libraries implement the json.Marshaler and json.Unmarshaler interfaces without having to import the "encoding/json" package because the function signatures only require built-in Go types.
However, I agree that the inconsistency between the bson.MarshalValue and MarshalBSONValue function signatures is confusing. We’re planning to resolve that inconsistency in Go Driver v3 (see GODRIVER-3642).