【问题标题】:How do I Unmarshal the bson from mongo of a nested interface with mgo?如何从带有mgo的嵌套接口的mongo中解组bson?
【发布时间】:2017-10-16 03:16:14
【问题描述】:

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

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

如何将嵌套接口映射到正确的结构?

【问题讨论】:

  • 你在寻找类似this的东西吗?
  • 不完全是,我想先把它带到一个 go 结构中,以便进行任何必要的处理。

标签: go mgo


【解决方案1】:

我认为显然无法实例化接口,因此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 规范。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2015-03-15
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2018-04-18
    相关资源
    最近更新 更多