【问题标题】:How to decode a string in a MongoDB document into a custom business struct in Go?如何将 MongoDB 文档中的字符串解码为 Go 中的自定义业务结构?
【发布时间】:2022-02-18 19:16:53
【问题描述】:

我有一个业务对象,它有一个字符串“代码”,它需要保存在我们 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"} 
}

我想注册一个转换器,将这个项目实例序列化为数据库集合:项目,

[
  {
    "name":"Abc",
    "code":"abccorp"
  }
]

我想注册一个转换器,将数据库中的项目文档反序列化为 Project 的一个实例。这个过程也必须反序列化 ClientCode 字段。

我无法在 MongoDB 的文档中找到有关为嵌入式 Go 结构实现自定义编码器/解码器的更多信息。我已经在基于 Kotlin 和 Spring Boot 的类似 webapi 服务中实现了自定义转换器。它使用注册的转换器并自动执行每个方向的转换。对于如何在 Go 中完成此任务的任何提示或建议,我将不胜感激。

感谢您的时间和兴趣, 迈克

【问题讨论】:

  • 自定义编组/解组逻辑可以通过实现bson.Marshalerbson.Unmashaler接口来实现。

标签: mongodb go serialization deserialization bson


【解决方案1】:

你可以实现 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
}

【讨论】:

  • 是的,我了解编组器的使用...问题似乎在于嵌入式结构具有自己的编组器并且父级具有其编组器时。看来这不是一个好的组合。我有一个解决方法,但似乎网络上可能还有其他一些选择。我看过很多使用标签的帖子: bson golang nested struct marshal 我将在空闲时间重新讨论这个问题。不过,感谢您的 cmets。
猜你喜欢
  • 2020-05-23
  • 1970-01-01
  • 2020-10-24
  • 2018-05-24
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 2018-02-04
  • 2014-01-18
相关资源
最近更新 更多