登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-26 22:30:37 174浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《如何将 MongoDB 文档中的字符串解码为 Go 中的自定义业务结构?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我有一个业务对象,它有一个字符串“代码”,需要将其保存在 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 中的自定义业务结构?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>