go - 如何使用 mgo 从嵌套接口(interface)的 mongo 解码 bson?

标签 go mgo

我有一组文档,其中包含我拥有的自定义接口(interface)类型的数组。下面的例子。我需要做什么才能从 mongo 中解码 bson,以便我最终可以返回 JSON 响应?

type Document struct {
  Props here....
  NestedDocuments customInterface
}

我需要做什么才能将嵌套接口(interface)映射到正确的结构?

最佳答案

我认为很明显接口(interface)不能被实例化,因此 bson 运行时不知道必须使用哪个 structUnmarshal 那个物体。此外,您的 customInterface 类型应该被导出(即使用大写字母“C”),否则它将无法从 bson 运行时访问。

我怀疑使用接口(interface)意味着 NestedDocuments 数组可能包含不同的类型,所有类型都实现了 customInterface

如果是这样的话,恐怕你将不得不做一些改变:

首先,NestedDocument 需要是一个包含文档的结构以及一些信息以帮助解码器了解什么是基础类型。像这样的东西:

type Document struct {
  Props here....
  Nested []NestedDocument
}

type NestedDocument struct {
  Kind string
  Payload bson.Raw
}

// Document provides 
func (d NestedDocument) Document() (CustomInterface, error) {
   switch d.Kind {
     case "TypeA":
       // Here I am safely assuming that TypeA implements CustomInterface
       result := &TypeA{}
       err := d.Payload.Unmarshal(result)
       if err != nil {
          return nil, err
       }
       return result, nil
       // ... other cases and default
   }
}

这样,bson 运行时将解码整个 Document,但将有效负载保留为 []byte

一旦解码了主要的Document,就可以使用NestedDocument.Document() 函数来获取struct 的具体表示.

最后一件事;当您保留您的Document 时,请确保将Payload.Kind 设置为3,这代表一个嵌入式文档。有关这方面的更多详细信息,请参阅 BSON 规范。

希望一切顺利,祝您的项目顺利。

关于go - 如何使用 mgo 从嵌套接口(interface)的 mongo 解码 bson?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762446/

相关文章:

mongodb - Go mgo 不存储对象

mongodb - 使用 Go 检索 MongoDB 文档时出现问题

unit-testing - 单元测试 golang 处理程序

go - 在 Go 中正确测量持续时间

sql-server - 备份 DBmssql : BACKUP DATABASE is terminating abnormally 时出现 Golang 错误

mongodb - mgo time.Time 或 bool 检查

mongodb - 如何在 Golang 的 mgo 查询中运行 $and 运算符

go - 无法通过 SSH 安装 go 模块(私有(private)嵌套存储库)

go - 在 golang 中强制传递依赖版本

Golang vips : How to render text with custom truetype font?