如何从mgo的嵌套接口的mongo解组bson?

时间:2017-10-16 03:16:15

标签: go mgo

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

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

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

1 个答案:

答案 0 :(得分:0)

我认为很明显,接口无法实例化,因此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设置为 3 ,这表示嵌入的文档。有关详细信息,请参阅BSON规范。

希望你的项目一切顺利,祝你好运。