首頁  >  文章  >  後端開發  >  如何使用介面透過 mgo 對 MongoDB 中不同類型的嵌入式節點進行建模?

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

DDD
DDD原創
2024-10-26 10:34:29761瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn