去获取字段类型

huangapple go评论70阅读模式
英文:

Go mgo get field type

问题

我正在使用Go和mgo作为存储引擎创建一个使用MongoDB的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))
        // 这里将进行类型检查
    }

    if limit, ok := (*fields)["limit"]; ok {
        limint, err := strconv.Atoi(limit.(string))
        if err != nil {...} // 错误处理
        delete(*fields, "limit")
        err = db.DB.C(collection).Find(fields).Limit(limint).All(&res)
        if err != nil {...} // 错误处理
    } else {
        err := db.DB.C(collection).Find(fields).All(&res)
        if err != nil {...} // 错误处理
    }

    resModel := ComputeModelSlice(res, collection)
    return resModel, nil
}

在MongoDB中,可以使用以下方式检查类型:

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

但是我找不到使用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

得分: 1

我不确定在执行查询之前如何获取字段的类型,但是一种方法是先查询到一个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:
    // 处理字符串类型
  case int:
    // 处理整数类型
  // ...
  default:
    // 处理其他类型
  }
}

请注意,这是一种可能的方法,但具体实现可能因你的代码和需求而有所不同。

英文:

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

huangapple
  • 本文由 发表于 2017年4月18日 21:08:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/43473122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定