我有一个包含我拥有的自定义接口类型数组的文档集合。下面的例子。我需要做什么来从mongo解组bson,以便最终返回JSON响应?如何使用mgo解组嵌套接口的mongo来解组bson?
type Document struct {
Props here....
NestedDocuments customInterface
}
我需要做什么来将嵌套接口映射到正确的结构?
我有一个包含我拥有的自定义接口类型数组的文档集合。下面的例子。我需要做什么来从mongo解组bson,以便最终返回JSON响应?如何使用mgo解组嵌套接口的mongo来解组bson?
type Document struct {
Props here....
NestedDocuments customInterface
}
我需要做什么来将嵌套接口映射到正确的结构?
我认为很明显,一个接口不能被实例化,因此bson
运行时不知道哪个struct
必须用于Unmarshal
那个对象。此外,您的customInterface
类型应该导出(即大写为“C”),否则将无法从bson
运行时访问。
我怀疑使用接口意味着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
设置为,它代表嵌入式文档。有关详细信息,请参阅BSON规范。
希望这是你的项目所有清楚和好运。
您是否在寻找[this](https://github.com/mongodb/mongo-tools/blob/master/common/bsonutil/converter.go)? –
并不完全,我想先把它带到一个结构体中去做任何必要的处理。 –