Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb Go mgo获取字段类型_Mongodb_Go_Mgo - Fatal编程技术网

Mongodb Go mgo获取字段类型

Mongodb Go mgo获取字段类型,mongodb,go,mgo,Mongodb,Go,Mgo,我正在使用MongoDB和mgo作为存储引擎在Go中创建一个API。 我为GET请求编写了一种抽象,允许用户按查询字符串参数中的字段过滤结果,但它只适用于字符串字段 我正在寻找一种只使用字段名获取字段类型的方法,以便在集合中搜索之前将参数强制转换为正确的类型。 代码如下: func (db *DataBase) GetByFields(fields *map[string]interface{}, collection string) ([]DataModel, error) { var

我正在使用MongoDB和mgo作为存储引擎在Go中创建一个API。 我为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合作。
有什么想法吗?

我不确定在执行查询之前获取字段类型的方法,但方法是简单地查询
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
  }
}