diff --git a/bson/decoder_test.go b/bson/decoder_test.go index 4cebea9d0e..e88aca6d6b 100644 --- a/bson/decoder_test.go +++ b/bson/decoder_test.go @@ -647,7 +647,8 @@ func TestDecoderConfiguration(t *testing.T) { var got objectIDTest err := dec.Decode(&got) - assert.EqualError(t, err, "error decoding key id: decoding an object ID to a non-hexadecimal string representation is not supported") + const want = "error decoding key id: decoding an object ID into a string is not supported by default (set Decoder.ObjectIDAsHexString to enable decoding as a hexadecimal string)" + assert.EqualError(t, err, want) }) t.Run("DefaultDocumentM top-level", func(t *testing.T) { t.Parallel() diff --git a/bson/string_codec.go b/bson/string_codec.go index a780677013..456028c1de 100644 --- a/bson/string_codec.go +++ b/bson/string_codec.go @@ -7,6 +7,7 @@ package bson import ( + "errors" "fmt" "reflect" ) @@ -50,14 +51,16 @@ func (sc *stringCodec) decodeType(dc DecodeContext, vr ValueReader, t reflect.Ty return emptyValue, err } case TypeObjectID: - oid, err := vr.ReadObjectID() - if err != nil { - return emptyValue, err - } if dc.objectIDAsHexString { + oid, err := vr.ReadObjectID() + if err != nil { + return emptyValue, err + } str = oid.Hex() } else { - return emptyValue, fmt.Errorf("decoding an object ID to a non-hexadecimal string representation is not supported") + const msg = "decoding an object ID into a string is not supported by default " + + "(set Decoder.ObjectIDAsHexString to enable decoding as a hexadecimal string)" + return emptyValue, errors.New(msg) } case TypeSymbol: str, err = vr.ReadSymbol()