我有以下(未经测试的)功能:
func Execute(task MyInterface) {
db := session.DB(task.Database()).C(task.Collection())
var tasks []MyInterface
db.Find(nil).All(&tasks)
for _, t := range tasks { t.Do() }
}
我想为我的函数提供一个实现接口(interface) MyInterface
的结构。然后它应该从 mongodb 检索一些值并调用检索到的结构的方法。
问题是 error: reflect.Set: value of type bson.M is not assignable to type mypkg.MyInterface
- 有什么方法可以让它工作吗?我尝试使用原始结构的类型实例化 tasks
,但无法使其正常工作。
任何帮助将不胜感激 - 谢谢 :)
最佳答案
mgo
无法创建 MyInterface
对象,因为 MyInterface 只是一个接口(interface)。尝试这样做:
myObject := &MyInterface{} //fails
我认为这基本上就是 mgo
尝试对其尝试解码的每条记录执行的操作。
要实现你想要的,制作 []map[string]interface{}
或 []bson.M
类型的任务
(后者是前者的别名)然后:
for _, o := range tasks {
t := &MyTypeThatImplementsMyInterface{
Field1 : o["my_field"],
//etc.
}
t.Do()
}
要么使 tasks
成为实现 MyInterface
及其字段的类型(var tasks []MyStructType
)对象的一部分匹配数据库中 bson 对象的键和值类型。如果您存储的数据是实现 MyInterface
的不止一种类型,这可能不起作用,因此上面的 slice of maps 选项。
此外,请谨慎使用 Find(nil).All(&tasks)
。如果您在该集合中有数百万条记录,根据记录大小,您可能会内存不足。
关于mongodb - 使用接口(interface)通过 mgo 从数据库中检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15004200/