我有一个业务对象,它有一个字符串"code",需要持久化到我们的MongoDB文档中。当文档从ClientCode获取时,我需要将代码转换为我们的MongoDB业务对象。
因此,更详细地说:
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"}
}我想注册一个转换器,它将这个Project实例序列化为数据库集合: projects,
[
{
"name":"Abc",
"code":"abccorp"
}
]我想注册一个转换器,它将数据库中的项目文档反序列化为Project的一个实例。这个过程也必须反序列化ClientCode字段。
我还没有在MongoDB文档中找到关于为嵌入式Go结构实现自定义编码器/解码器的很多信息。我在类似的基于Kotlin和Spring的webapi服务中实现了自定义转换器。它使用注册转换器,并在每个方向自动执行转换。对于如何在Go中完成这项任务,我会非常感激的。
谢谢你的时间和兴趣,迈克
发布于 2022-02-18 11:16:53
可以实现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
}https://stackoverflow.com/questions/71172107
复制相似问题