首页 > 后端开发 > 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) 中作为模型的接口类型

问题:

在一个场景中涉及工作流和各种类型的嵌入节点,使用 mgo 接口在 MongoDB 中建模节点会导致错误。发生错误的原因是 mgo 无法在没有类型信息的情况下解组嵌入的 Node 文档。

解决方案:

要克服此限制,请考虑定义一个结构体来保存 Node 类型以及关联的类型信息:

<code class="go">type NodeWithType struct {
   Node Node `bson:"-"`
   Type string
}</code>
登录后复制

在 Workflow 结构体中,使用 NodeWithType 结构体数组来存储节点:

<code class="go">type Workflow struct {
   CreatedAt time.Time
   StartedAt time.Time
   CreatedBy string
   Nodes []NodeWithType
}</code>
登录后复制

要正确解码数据,请实现 SetBSON 函数on NodeWithType:

<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>
登录后复制

此方法允许 mgo 根据 NodeWithType 结构中存储的类型信息正确解组嵌入节点。

以上是如何使用接口通过 mgo 对 MongoDB 中不同类型的嵌入式节点进行建模?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!