小编sha*_*nit的帖子

如何在mgo(Go)中使用接口类型作为模型?

假设您的工作流由多个不同类型的嵌入式节点组成.由于节点的类型不同,我想在这里使用Golang接口并提出以下内容:

type Workflow struct {
   CreatedAt time.Time
   StartedAt time.Time
   CreatedBy string
   Nodes []Node
}

type Node interface {
  Exec() (int, error)
}

type EmailNode struct {
   From string
   To string
   Subject string
   Body string
}

type TwitterNode struct {
   Tweet string
   Image []byte
}

func (n *EmailNode) Exec() (int, error){
   //send email
   return 0, nil
}

func (n *TwitterNode) Exec() (int, error) {
   //send tweet
   return 0, nil
}
Run Code Online (Sandbox Code Playgroud)

这些工作流程存储在MongoDB中,我有样本种子数据.使用mgo,当我尝试查找工作流程(给定其ID)时:

w = &Workflow{}
collection.FindID(bson.ObjectIdHex(id)).One(w)
Run Code Online (Sandbox Code Playgroud)

我得到错误 - 类型bson.M的值不能分配给类型Node.

我觉得mgo如何在没有任何类型信息的情况下将嵌入式Node文档解组为Go结构,这也让我觉得有点奇怪.可能我需要从另一个角度来看问题.

任何建议都将受到高度赞赏.

go mongodb mgo

5
推荐指数
2
解决办法
2814
查看次数

标签 统计

go ×1

mgo ×1

mongodb ×1