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的方式。 有什么想法?