Go mgo获取字段类型

I'm creating an API in Go using MongoDB and mgo as storage engine. I wrote sort of an abstraction for GET requests letting user filter the results by fields in query string parameters, but it only works for string fields.

I'm searching for a way to get a field's type with only field name, in order to cast parameter to correct type before searching in collection. Here is the code:

func (db *DataBase) GetByFields(fields *map[string]interface{}, collection string) ([]DataModel, error) {
    var res []interface{}

    Debug("Getting " + collection + " by fields: ")
    for i, v := range *fields {
        Debug("=> " + i + " = " + v.(string))
        // Here would be the type checking

    if limit, ok := (*fields)["limit"]; ok {
        limint, err := strconv.Atoi(limit.(string))
        if err != nil {...} // Err Handling
        delete(*fields, "limit")
        err = db.DB.C(collection).Find(fields).Limit(limint).All(&res)
        if err != nil {...} // Err Handling
    } else {
        err := db.DB.C(collection).Find(fields).All(&res)
        if err != nil {...} // Err Handling

    resModel := ComputeModelSlice(res, collection)
    return resModel, nil

With mongodb I can check type with:

db.getCollection('CollectionName').findOne().field_name instanceof typeName

But I can't find a way to perform that with mgo. Any idea?

2017/04/18 13:08
  • mongodb
  • 点赞
  • 收藏
  • 回答