我有一组文档,其中包含我拥有的自定义接口(interface)类型的数组。下面的例子。我需要做什么才能从 mongo 中解码 bson,以便我最终可以返回 JSON 响应?
type Document struct {
Props here....
NestedDocuments customInterface
}
我需要做什么才能将嵌套接口(interface)映射到正确的结构?
最佳答案
我认为很明显接口(interface)不能被实例化,因此 bson
运行时不知道必须使用哪个 struct
来Unmarshal
那个物体。此外,您的 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/