[GODRIVER-1029] BSON marshaling does not know how to handle common Go patterns such as struct composition Created: 09/May/19 Updated: 16/Nov/21 Resolved: 27/Jun/19 |
|
| Status: | Closed |
| Project: | Go Driver |
| Component/s: | BSON |
| Affects Version/s: | None |
| Fix Version/s: | None |
| Type: | Bug | Priority: | Major - P3 |
| Reporter: | Quest Henkart | Assignee: | Divjot Arora (Inactive) |
| Resolution: | Done | Votes: | 0 |
| Labels: | mgocompat | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Epic Link: | mgo migration tool |
| Description |
|
In Go, struct composition is extremely common. Embedding a struct into another struct is the only way we can achieve some level of subclassing and inheritance in the language.
It appears the BSON marshalers are not prepared to handle this at all. In most cases, the fields are just completely ignored. In other cases, it includes a hidden field name.
I expect the bson marshaller to handle structs in the same way as the Golang JSON marshaller. I have created a gist to express the JSON behavior https://gist.github.com/qhenkart/2c4fd696d1450ac266a09d1c62d4f67a
The exact same code with bson tags and the mongo library will be completely ignored by the bson marshaller. The final document that is inserted is simply empty. There are a lot of different variations of struct composition, and the BSON marshaller must know how to handle them.
Additionally, I recently tried extending primitive.ObjectId, to create a workaround on another issue I posted recently. I extended it as follows `type ObjectID struct { primitive.ObjectID}`
This allows me to overwrite or add methods to the class and inherit all of the behavior of the primitive.ObjectID. It works great except the BSON marshaller doesn't ignore it in this case. In this case it would insert something along the lines of `id: {objectId: ObjectId("<validobjectid>")} |
| Comments |
| Comment by Divjot Arora (Inactive) [ 06/Jun/19 ] |
|
qhenkart Our BSON machinery does not marshal or unmarshal private fields. For embedded structs, our default behavior is to include an extra key as the struct name and an embedded document as the value. If you do not want to include the extra key, you can specify the `bson:"inline"` struct tag for embedded fields. |