如何使用mgo解组嵌套接口的mongo来解组bson?

问题描述:

我有一个包含我拥有的自定义接口类型数组的文档集合。下面的例子。我需要做什么来从mongo解组bson,以便最终返回JSON响应?如何使用mgo解组嵌套接口的mongo来解组bson?

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

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

+0

您是否在寻找[this](https://github.com/mongodb/mongo-tools/blob/master/common/bsonutil/converter.go)? –

+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设置为,它代表嵌入式文档。有关详细信息,请参阅BSON规范。

希望这是你的项目所有清楚和好运。