首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将MongoDB文档中的字符串解码为Go中的自定义业务结构?

如何将MongoDB文档中的字符串解码为Go中的自定义业务结构?
EN

Stack Overflow用户
提问于 2022-02-18 10:41:31
回答 1查看 226关注 0票数 1

我有一个业务对象,它有一个字符串"code",需要持久化到我们的MongoDB文档中。当文档从ClientCode获取时,我需要将代码转换为我们的MongoDB业务对象。

因此,更详细地说:

代码语言:javascript
复制
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,

代码语言:javascript
复制
[
  {
    "name":"Abc",
    "code":"abccorp"
  }
]

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

我还没有在MongoDB文档中找到关于为嵌入式Go结构实现自定义编码器/解码器的很多信息。我在类似的基于Kotlin和Spring的webapi服务中实现了自定义转换器。它使用注册转换器,并在每个方向自动执行转换。对于如何在Go中完成这项任务,我会非常感激的。

谢谢你的时间和兴趣,迈克

EN

回答 1

Stack Overflow用户

发布于 2022-02-18 11:16:53

可以实现BSON接口。

代码语言:javascript
复制
// 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)
}
代码语言:javascript
复制
// 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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71172107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档