创建通用函数-官方MongoDB驱动程序 [英] Create generic function - Official MongoDB Driver

查看:95
本文介绍了创建通用函数-官方MongoDB驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用来自globalsign的mgo驱动程序时,无论我使用什么模型,我都可以节省一些时间来重新使用函数以返回集合中的所有元素.

when using the mgo driver from globalsign, i could save some time reusing a function to return all the elements from a collection, no matter what models i was using.

但是现在,使用MongoDB的Official Driver,我需要具体说明我要解码的接口,因此无法将这种方法用于其他接口.

But now, with the Official Driver from MongoDB, i need to specific which interface I want to decode, so in this way I can't reuse this method for other interfaces.

有人到这一点吗?

使用mgo驱动程序的功能:

Function using the mgo driver:

func ReturnAll(collection string, model interface{}, skip int, limit int) error {
 session := GetSession()
 defer session.Close()
 return session.DB(DBName).C(collection).Find(nil).Skip(skip).Limit(limit).All(modelo)
}

推荐答案

使用

Use Cursor.All in version >= 1.1.0 of the driver:

var result []Example
err := cursor.All(&result)
if err != nil {
    // handle error
}

对于早期版本, 使用 reflect 包将所有值解码为切片:

For earlier versions, use the reflect package to decode all values to a slice:

// decodeAll decodes all values to the slice pointed to by result.
func decodeAll(cur *mongo.Cursor, result interface{}) error {
    rv := reflect.ValueOf(result).Elem()

    // reset to beginning of the slice.
    sv := rv.Slice(0, rv.Cap())

    for cur.Next(context.Background()) {

        // Allocate new element value and decode to it.
        pev := reflect.New(sv.Type().Elem())
        if err := cur.Decode(pev.Interface()); err != nil {
            return err
        }

        // Append the element value.
        sv = reflect.Append(sv, pev.Elem())
    }

    rv.Set(sv)
    return cur.Err()
}

这样称呼:

var result []Example
err := decodeAll(cursor, &result)
if err != nil {
    // handle error
}

这篇关于创建通用函数-官方MongoDB驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆