创建通用函数-官方MongoDB驱动程序

创建通用函数-官方MongoDB驱动程序,mongodb,go,Mongodb,Go,当使用globalsign的mgo驱动程序时,我可以节省一些时间,重用函数返回集合中的所有元素,而不管我使用的是什么模型 但是现在,有了MongoDB的官方驱动程序,我需要指定要解码的接口,所以这样我就不能在其他接口上重用这个方法 有人提到这一点吗 使用mgo驱动程序的功能: func ReturnAll(collection string, model interface{}, skip int, limit int) error { session := GetSession() def

当使用globalsign的mgo驱动程序时,我可以节省一些时间,重用函数返回集合中的所有元素,而不管我使用的是什么模型

但是现在,有了MongoDB的官方驱动程序,我需要指定要解码的接口,所以这样我就不能在其他接口上重用这个方法

有人提到这一点吗

使用mgo驱动程序的功能:

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)
}
在版本>=1.1.0的驱动程序中使用:

var result []Example
err := cursor.All(&result)
if err != nil {
    // handle error
}
对于早期版本, 使用包将所有值解码为一个片段:

// 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
}
在版本>=1.1.0的驱动程序中使用:

var result []Example
err := cursor.All(&result)
if err != nil {
    // handle error
}
对于早期版本, 使用包将所有值解码为一个片段:

// 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
}