2017-10-16 35 views
0

我有一個包含我擁有的自定義接口類型數組的文檔集合。下面的例子。我需要做什麼來從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

並不完全,我想先把它帶到一個結構體中去做任何必要的處理。 –

回答

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規範。

希望這是你的項目所有清楚和好運。