I’m trying to add a custom encoder and decoder for a Golang struct type, which must be stored in Mongo as a string. Previously, our mongo driver used no custom encoders (only the BSONOptions configuration) and was configured like so:
bsonOptions := &options.BSONOptions{
NilMapAsEmpty: true,
NilSliceAsEmpty: true,
}
client, err := gomongo.Connect(context.Background(),
options.Client().
ApplyURI(m.config.MongoURL).
SetWriteConcern(writeconcern.Majority()).
SetReadConcern(readconcern.Majority()).
SetBSONOptions(bsonOptions))
I have now changed this to:
bsonOptions := &options.BSONOptions{
NilMapAsEmpty: true,
NilSliceAsEmpty: true,
}
client, err := gomongo.Connect(context.Background(),
options.Client().
ApplyURI(m.config.MongoURL).
SetWriteConcern(writeconcern.Majority()).
SetReadConcern(readconcern.Majority()).
SetBSONOptions(bsonOptions).
SetRegistry(buildRegistry()))
where the buildRegistry funciton is defined as:
func buildRegistry() *bsoncodec.Registry {
registry := bsoncodec.NewRegistry()
registry.RegisterTypeEncoder(reflect.TypeOf(arns.ARN{}),
bsoncodec.ValueEncoderFunc(arnsEncodeValue))
registry.RegisterTypeDecoder(reflect.TypeOf(arns.ARN{}),
bsoncodec.ValueDecoderFunc(arnsDecodeValue))
return registry
}
(I’m leaving out the definitions of arnsDecodeValue and arnsEncodeValue for brevity, but can include them if they’re relevant.)
arns.ARN is a struct type. If I comment out the four lines that register the encoder and decoder, so that I’m just using a default registry, everything works as it always has. As soon as I register either an encoder or a decoder, however, every single attempt to query data from the backend results in an identical error message:
cannot marshal type primitive.M to a BSON Document: no encoder found for primitive.M
It seems as though the addition of a single type-encoder (or decoder) overrides the Registry’s ability to find and use the default decoder for the basic primitive types. It’s not clear to me if this is a bug or if something is misconfigured, and any help or advice would be greatly appreciated.