首頁 > 後端開發 > Golang > 主體

如何使用介面透過 mgo 對 MongoDB 中不同類型的嵌入式節點進行建模?

DDD
發布: 2024-10-26 10:34:29
原創
769 人瀏覽過

How to Model Embedded Nodes of Different Types in MongoDB with mgo using Interfaces?

mgo (Go) 中作為模型的介面類型

問題:

問題:

在一個🎜>問題:

在一個🎜>問題:
<code class="go">type NodeWithType struct {
   Node Node `bson:"-"`
   Type string
}</code>
登入後複製

在一個場景中涉及工作流程和各種類型的嵌入節點,使用mgo 介面在MongoDB 中建模節點會導致錯誤。發生錯誤的原因是 mgo 無法在沒有類型資訊的情況下解組嵌入的 Node 文件。
<code class="go">type Workflow struct {
   CreatedAt time.Time
   StartedAt time.Time
   CreatedBy string
   Nodes []NodeWithType
}</code>
登入後複製

解決方案:
<code class="go">func (nt *NodeWithType) SetBSON(r bson.Raw) error {
   // Decode the type string
   typeStr := r.String()

   // Create a new Node value based on the type string
   switch typeStr {
   case "EmailNode":
      nt.Node = &EmailNode{}
   case "TwitterNode":
      nt.Node = &TwitterNode{}
   default:
      return errors.New("Unknown node type")
   }

   // Unmarshal the remaining data to the Node value
   bsonBytes, err := bson.Marshal(r.Body)
   if err != nil {
      return err
   }
   return bson.Unmarshal(bsonBytes, nt.Node)
}</code>
登入後複製

要克服此限制,請考慮定義一個結構體來保存Node 類型以及關聯的類型資訊:在Workflow 結構體中,使用NodeWithType 結構體數組來儲存節點:要正確解碼數據,請實作SetBSON 函數on NodeWithType:此方法允許讓mgo根據NodeWithType 結構中儲存的類型資訊正確解組嵌入節點。

以上是如何使用介面透過 mgo 對 MongoDB 中不同類型的嵌入式節點進行建模?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!