Mongodb 如何在mgo(Go)中使用接口类型作为模型?
假设您有一个由多个不同类型的嵌入式节点组成的工作流。由于节点的类型不同,我考虑在这里使用Golang接口,并提出以下建议:Mongodb 如何在mgo(Go)中使用接口类型作为模型?,mongodb,go,mgo,Mongodb,Go,Mgo,假设您有一个由多个不同类型的嵌入式节点组成的工作流。由于节点的类型不同,我考虑在这里使用Golang接口,并提出以下建议: type Workflow struct { CreatedAt time.Time StartedAt time.Time CreatedBy string Nodes []Node } type Node interface { Exec() (int, error) } type EmailNode struct { From s
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中,我在其中有样本种子数据。使用mgo,当我尝试查找工作流(给定其ID)时:
我得到了错误-类型bson.M的值不能分配给类型Node
mgo如何在没有任何类型信息的情况下将嵌入的节点文档解组到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 {
}
按照Simon Fox关于
SetBSON
实施的回答,这里有一个更准确的答案
让我们看一下原始代码:
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
}
现在要做的是:从Mongo解组BSON对象后,您希望能够知道每个节点是EmailNode
还是TwitterNode
当您将节点存储为节点
接口时,mgo无法知道要实现什么结构,因此必须明确地告诉它。这里有SetBSON
在您的示例中,问题来自此工作流.Nodes
,它是节点
接口的一部分。由于它是一个简单的切片,最好是创建一个自定义类型,mgo在解组BSON时可以调用该类型:
type NodesList []Node
// The updated Workflow struct:
type Workflow struct {
CreatedAt time.Time
StartedAt time.Time
CreatedBy string
Nodes NodesList
}
现在,您可以在此NodesList
上实现SetBSON
,并描述其工作原理。请注意,在使用指针时,可以定义变量中包含的内容:
// Note that you must use a pointer to the slice
func (list *NodesList) SetBSON(raw raw.BSON) error {
// Now you need to create the objects according to your
// own domain logic and what's contained inside "raw":
if raw.something {
*list = append(*list, &TwitterNode{})
} else {
*list = append(*list, &EmailNode{})
}
return nil
}
你能举例说明如何实现setBSON功能吗?我不知道如何解码类型字符串。
// Note that you must use a pointer to the slice
func (list *NodesList) SetBSON(raw raw.BSON) error {
// Now you need to create the objects according to your
// own domain logic and what's contained inside "raw":
if raw.something {
*list = append(*list, &TwitterNode{})
} else {
*list = append(*list, &EmailNode{})
}
return nil
}