[GODRIVER-1159] MarshalBSONValue With Embedded struct Created: 23/Jun/19  Updated: 11/Sep/19  Resolved: 12/Aug/19

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

Type: Task Priority: Major - P3
Reporter: Benny Leung Assignee: Run Tian Yu (Inactive)
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Mongodb: 4.0.5
Go-Driver: 1.0.3
Golang: 1.12



 Description   

Hi, i want to custom MarshalBSONValue like GODRIVER-980

 

type StructA struct {
    ID `bson:"_id"` // <-- Embedded
    Foo string `bson: "Foo"`
}
 
type ID string 
 
func (e ID) MarshalBSONValue() (bsontype.Type, []byte, error) {
    return bsontype.String, bsoncore.AppendString(nil, string(e)), nil
}

 

 

But my struct is embedded, it said

cannot transform type *main.StructA to a BSON Document: WriteValueBytes can only write while positioned on a Element or Value but is positioned on a TopLevel

What should i do?



 Comments   
Comment by Benny Leung [ 28/Jun/19 ]

Hi Connie Yu

It work, Thanks a lot.

Please close the issue.

 

 

Fixed Code After Suggestion:

https://github.com/xlebenny/GODRIVER-1159/commit/d1e074777fd5ba71b14b3e18b7c8f9da343347fd

Comment by Run Tian Yu (Inactive) [ 26/Jun/19 ]

Hi xlebenny,

The issue is that when there's an embedded field with a custom marshaller in a struct, our encoding system attempts to use the inherited custom marshaller to encode the entire struct instead of just the embedded field. 

To get around this, we can explicitly register the default StructCodec for the StructA type and only use the custom marshaller for the embedded field like so:

sc, _ := bsoncodec.NewStructCodec(bsoncodec.DefaultStructTagParser) 
reg := bson.NewRegistryBuilder().RegisterEncoder(reflect.TypeOf(StructA{}), sc).Build()

In the case of *StructA, we can similarly register a Pointer encoder.

Comment by Benny Leung [ 23/Jun/19 ]

Code also uploaded to https://github.com/xlebenny/GODRIVER-1159/commit/dd91bef8730adb616eac197103d451994c6ec1bb

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