假设您的工作流由多个不同类型的嵌入式节点组成。由于节点是不同类型的,因此我想到在这里使用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
}
这些工作流存储在MongoDB中,并且我有示例种子数据。当我尝试查找工作流程(使用其ID)时,使用mgo:
w = &Workflow{}
collection.FindID(bson.ObjectIdHex(id)).One(w)
我收到错误-bson.M类型的值不可分配给Node类型。
对于我来说,如何在没有任何类型信息的情况下如何将嵌入式Node文档解组到Go结构中也让我感到有些奇怪。可能我需要从另一个角度看问题。
任何建议将不胜感激。
由于您提到的原因,您不能在文档中使用界面。解码器没有有关要创建的类型的信息。
一种解决方法是定义一个结构来保存类型信息:
type NodeWithType struct {
Node Node `bson:"-"`
Type string
}
type Workflow struct {
CreatedAt time.Time
StartedAt time.Time
CreatedBy string
Nodes []NodeWithType
}
在此类型上实现SetBSON函数。此函数应解码类型字符串,根据该字符串创建正确类型的值,然后解组为该值。
func (nt *NodeWithType) SetBSON(r bson.Raw) error {
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句