doremifasodo0008008 2017-04-18 13:08
浏览 65

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?

  • 写回答

1条回答 默认 最新

  • dsmvovm27249 2017-04-18 16:08
    关注

    I'm not sure about a way to get the type of the field before doing the query, but one approach is to simply query into an bson.M and then do type detection on the retrieved values:

    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
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?