1

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?

JM445
  • 168
  • 1
  • 12

1 Answers1

1

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
  }
}
Community
  • 1
  • 1
John Weldon
  • 39,849
  • 11
  • 94
  • 127