0
votes

I am building a bson map in golang using mgo library. I want to refactor some code to be able to avoid duplication.

Consider this:

    bson.M {
         "$match" : bson.M{
            "xyz" : "abc",
          },
          "$id_1" : value_1, 
    }

and another bson map of type:

    bson.M {
         "$match" : bson.M{
            "xyz" : "abc",
          },
          "$id_2" : value_2,
    }

How can I combine the two (build bson.M from a function and return, value1/2 are params to this func) to be used based on if value_1 is empty string or value_2 is empty string.

For example: if I build a the following function. My intention is to build map of first type (see above) by calling buildBsonObject("123","") and the second one by calling buildBsonObject("", "456").

func buildBsonObject (value_1 string, value_2 string) {    
    return bson.M {
             "$match" : bson.M{
                "xyz" : "abc",
              },
              "$id_1" : value_1, 
              "$id_2" : value_2,
        }
}

If I do the following (see function buildBsonObject), then when value_1 is empty string, my mongo aggregation query will not work since it will treat as id_1 being "", whereas I intended to just have id_2 in my bson object.

Any suggestions on how to do this. Thanks.

1

1 Answers

0
votes

How about this:

func buildBsonObject(value_1 string, value_2 string) bson.M {
  m := bson.M{
    "$match": bson.M{
        "xyz": "abc",
    },
  }
  if value_1 != "" {
    m["$id_1"] = value_1
  }
  if value_2 != "" {
    m["$id_2"] = value_2
  }
  return m
}

playground example

An alternative is to pass the key name to the function:

func buildBsonObject(k string, v string) bson.M {
  return bson.M{
    "$match": bson.M{
        "xyz": "abc",
    },
    k: v,
  }
}

playground example