2017-04-18 46 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 
    } 
}