Utilizing Filters with a Golang Rest API

Project Repo:

I’m trying to create a route to filter results on the server before returning the json.

Here’s a gist of my first attempt: Filter Functions with Filter Type
I’ve removed the bson.M from the filter. Now the code creates an internal server error.
@nraboy

Hi @awe_ful (nice nickname :smiley: !) and welcome in the MongoDB Community :muscle: !

We have a Go code sample here that is using filters.

Hopefully this helps.
More about the MongoDB Open Data COVID-19 project in the DevHub :slight_smile:.

Cheers,
Maxime.

Hey @awe_ful,

Thanks for taking our Twitter conversation to the forums. To fill in any missing context for users with similar questions, a digest of our conversation on Twitter is as follows:

@nraboy
I saw some of your #mongodb #golang tutorials. Have you tried doing any filter queries?

What are you interested in?

Gist: https://bit.ly/2ZGHbHK I’m trying filter transactions but I’m getting a missing key in map literalcompiler error. They’re financial tranx & I’d like to be able to filter by vendor, budget, etc. Curious if you or anyone else has tried it. I’ve done it in js before.

Since your struct has the BSON annotations you don’t need to wrap the filter in bson.M. If that doesn’t work, create a thread on http://community.mongodb.com and tag me. I’ll check it in more detail in the morning.

So I had a look at your Gist. I believe the problem is because you’re using pointers for each of your FilterTransaction fields and are not properly dereferencing them when trying to use them. I’m also not sure BSON annotations will work on pointer variable types.

So we have a few options:

  1. You can remove the pointers from each field in your FilterTransaction struct and everything should work fine after that.
  2. Instead of populating a filter variable of type FilterTransaction, use bson.M as the type instead and add the dereferenced fields from the filterTranx variable.

If you go with option #1, you don’t need to be checking if nil for each field because you have the omitempty on the field. It will be ignored anyways with that field so you are doing double the work.

In regards to dereferencing in option #2, I mean something like this:

// ...

filter := bson.M{}

if filterTranx.BudgetID != nil {
    filter["budget_id"] = *filterTranx.BudgetID
}

// ...

I’d go with option #1 if you can.

Let me know if you’re still stuck.

Best,

2 Likes

Thank you. I’ll check it out.
I’m thinking that the issue isn’t with MongoDB, but with the decoder.