Search code examples
mongodbpointersgoslicemgo

Golang MongoDB using $in operator on list - result argument must be a slice address


I have the following Mongo query I'm trying to translate to Go using github.com/globalsign/mgo:

db.getCollection('cluster').find({"clusterName": {"$in": ["clusterA", "clusterB"]}})

"clusterName" is a string field. Basically the naive alternative would be to perform multiple calls to mongo for each value in the list.

The query I wrote:

func ReadClusters(clusterNames []string) (*[]kusto.Cluster, error) {
    var clusters *[]kusto.Cluster
    err := readObjects(clusterCollection, bson.M{"clusterName": bson.M{"$in": clusterNames}}, &clusters, "" /* sortField */)
    if err != nil {
        return nil, err
    }

    return clusters, nil
}

And my helper functions:

func readObjects(collection string, query bson.M, dest interface{}, sortField string) error {
    err := getDocuments(collection, query, dest, sortField)
    if err != nil {
        if err == mgo.ErrNotFound {
            return ErrNotFound
        }
        return err
    }

    return nil
}

func getDocuments(collectionName string, query bson.M, dest interface{}, sortField string) error {
    session := client.Copy()
    defer session.Close()

    collection := getCollection(session, collectionName)
    find := collection.Find(query)

    if sortField != "" {
        find = find.Sort(sortField)
    }

    return find.All(dest)
}

I'm getting the error:

2020/07/09 11:58:46 http: panic serving [::1]:54085: result argument must be a slice address

I'm currently using Go1.11, and the mgo version I see under go.mod is github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8


Solution

  • clusters is already of pointer type to slice, so taking its address will be a pointer to pointer to slice.

    Declare it to be a non-pointer to slice:

    var clusters []kusto.Cluster