
本文介绍在使用 mgo 驱动时,如何区分结构体值与指针类型并实现差异化 bson 序列化——核心方案是为指针语义创建独立包装类型,并通过实现 getbson/setbson 接口控制其序列化行为。
在 MongoDB 的 Go 生态中,mgo(尽管已归档,但在遗留项目中仍广泛使用)默认将结构体字段(无论是否为指针)统一内联为嵌套文档。例如:
type Tool struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string `bson:"name"`
Type string `bson:"type"`
}
type Order struct {
Item Tool `bson:"item"`
AssociatedItem *Tool `bson:"associated_item"` // 期望只存 ID,但实际仍嵌入整个 Tool
}此时 AssociatedItem 字段虽为 *Tool,mgo 在 MarshalBSON 过程中仍会解引用并递归序列化整个 Tool 结构,无法满足“仅保存引用 ID”的常见业务需求(如避免数据冗余、实现松耦合关联)。
根本限制在于:mgo 的 GetBSON() / SetBSON() 接口作用于类型本身,而非接收者是否为指针。即 func (t Tool) GetBSON() 对 Tool 和 *Tool 均生效,无法天然区分语义。
✅ 推荐解决方案:引入语义专用包装类型
通过定义一个新类型(如 SelectiveTool),显式承载“需按引用序列化”的语义,并为其单独实现 GetBSON:
type SelectiveTool Tool // 类型别名,不继承方法
// GetBSON 控制序列化:仅输出 ID 字段
func (st *SelectiveTool) GetBSON() (interface{}, error) {
if st == nil {
return nil, nil
}
return bson.M{"_id": (*Tool)(st).ID}, nil
}
// SetBSON 控制反序列化:从 BSON 中提取 ID 并构造 *Tool(需额外加载)
func (st *SelectiveTool) SetBSON(raw bson.Raw) error {
var doc bson.M
if err := raw.Unmarshal(&doc); err != nil {
return err
}
if id, ok := doc["_id"]; ok {
// 注意:此处仅恢复 ID,完整 Tool 需后续按需查询
*st = SelectiveTool{ID: id.(bson.ObjectId)}
}
return nil
}
// 使用示例
type Order struct {
Item Tool `bson:"item"`
AssociatedItem *SelectiveTool `bson:"associated_item"` // ✅ 现在仅存 {"_id": "..."}
}? 关键说明与注意事项:
- SelectiveTool 是 Tool 的新类型(type alias),而非别名(type SelectiveTool = Tool),因此不会继承 Tool 的 GetBSON 方法,确保自定义逻辑生效;
- GetBSON 返回 bson.M{"_id": ...} 实现了“引用式存储”,符合 MongoDB 中常见的 ObjectId 关联模式;
- SetBSON 仅恢复 ID,真实业务中通常需配合服务层逻辑(如 FindById)按需加载完整 Tool 实例,体现懒加载思想;
- 若需支持零值安全,请在 GetBSON 中显式判空(如 if st == nil { return nil, nil });
- 此方案完全兼容 mgo 的反射序列化流程,无需修改驱动或使用钩子函数,简洁且可预测。
综上,当需要对指针字段施加不同于值字段的序列化策略时,基于类型隔离的包装法是最清晰、最可控的实践方式——它将语义差异转化为类型差异,让序列化逻辑明确、可测试、易维护。










