2017-04-18 84 views
1

我使用MongoDB和mgo作为存储引擎在Go中创建API。 我写了一种GET请求抽象,让用户可以按查询字符串参数中的字段过滤结果,但它只适用于字符串字段。Go mgo get字段类型

我正在寻找一种方法来获取只有字段名称的字段类型,才能在集合中搜索之前将参数强制转换为正确的类型。 下面是代码:

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 
} 

随着MongoDB的我可以检查类型:

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

但我找不到执行与MgO的方式。 有什么想法?

回答

1

我不知道的方式之前得到现场的类型做查询,但one方法是简单地查询到bson.M,然后就在检索到的值类型检测:

var res bson.M 
// ... 
err = db.DB.C(collection).Find(fields).Limit(limint).All(&res) 
// ... 
for key, val := range res { 
    switch val.(type) { 
    case string: 
    // handle 
    case int: 
    // handle 
    // ... 
    default: 
    // handle 
    } 
}