问题内容
我有一个业务对象,它有一个字符串“代码”,需要将其保存在 mongodb 的文档中。当从 mongodb 获取文档时,我需要将代码转换为我们的 clientcode 业务对象。
所以,更详细地说:
business objects - simplified
type clientcode struct {
code string `bson:"code" json:"code"`
}
type project struct {
name string `bson:"name" json:"name"`
code clientcode `bson:"clientcode" json:"clientcode"`
}
p := project{
name: "abc",
code: clientcode{code: "abccorp"}
}
我想注册一个转换器,将项目的此实例序列化为数据库集合:projects,
[
{
"name":"Abc",
"code":"abccorp"
}
]
我想注册一个转换器,将数据库中的项目文档反序列化为 project 实例。此过程还必须反序列化 clientcode 字段。
我在 mongodb 文档中找不到太多有关为嵌入式 go 结构实现自定义编码器/解码器的信息。我已经在基于 kotlin 和 spring boot 的类似 webapi 服务中实现了自定义转换器。它使用注册转换器并自动执行每个方向的转换。我非常感谢任何有关如何在 go 中完成此任务的推动或建议。
感谢您的时间和兴趣, 迈克
正确答案
你可以实现bson接口
// bson/marshal.go
// marshaler is an interface implemented by types that can marshal themselves
// into a bson document represented as bytes. the bytes returned must be a valid
// bson document if the error is nil.
type marshaler interface {
marshalbson() ([]byte, error)
}
// bson/unmarshal.go
// Unmarshaler is an interface implemented by types that can unmarshal a BSON
// document representation of themselves. The BSON bytes can be assumed to be
// valid. UnmarshalBSON must copy the BSON bytes if it wishes to retain the data
// after returning.
type Unmarshaler interface {
UnmarshalBSON([]byte) error
}
理论要掌握,实操不能落!以上关于《如何将 MongoDB 文档中的字符串解码为 Go 中的自定义业务结构?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注公众号吧!