首页 文章

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

提问于
浏览
0

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

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

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

1 回答

  • 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规范 .

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

相关问题