普通网友 2013-02-21 14:03
浏览 62

使用界面通过mgo从数据库检索

I have following (untested) function:

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() }
}

I want to give my function a struct that implements interface MyInterface. It should then retrieve some values from mongodb and call a method on the retrieved structs.

Problem is error: reflect.Set: value of type bson.M is not assignable to type mypkg.MyInterface - is there some way to make this work? I tried to instantiate tasks using the type of the original struct, but couldn't get it working.

Any help would be appreciated - thanks :)

  • 写回答

1条回答 默认 最新

  • drxdai15012937753 2013-02-21 15:22
    关注

    mgo can't create MyInterface objects since MyInterface is just an interface. Try doing :

    myObject := &MyInterface{}  //fails
    

    I think it's basically what mgo is trying to do for each record it tries to unmarshal.

    To achieve what you want, make tasks of type []map[string]interface{} or []bson.M (the latter is an alias for the former) and then:

    for _, o := range tasks {
        t := &MyTypeThatImplementsMyInterface{ 
            Field1 : o["my_field"],
            //etc.  
        } 
        t.Do()
    }
    

    Either that or make tasks a slice of objects of a type (var tasks []MyStructType) that implements MyInterface and that its fields match the keys and values types of your bson objects in your database. That might not work if your stored data is of more than one type implementing MyInterface, hence the slice of maps option above.

    Also, be cautious with Find(nil).All(&tasks). If you have millions of records in that collection, depending on the records size, you may fall short of memory.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集