Go 里给 MongoDB 存自定义值类型(比如包装了第三方金额库的Money)时,通常要实现 BSON 序列化接口。一个经典需求:字段是指针,值为 nil 时文档里要落成price: null,而不是报错、也不是把字段省略。在 mongo-driver v2 上,照 v1 经验实现的MarshalBSON会在 nil 分支上连环踩坑。
问题现象
模型与自定义编码如下:
typemoneyFieldsstruct{Amountint64`json:"amount" bson:"amount"`Currencystring`json:"currency" bson:"currency"`}typeMoney