This story was moved to: https://jonathancardoso.com/en/blog/introduction-graphql-mongo-helpers/

If you are using MongoDB and GraphQL, you probably have some arguments on your resolvers to filter the data returned from MongoDB. Using those helpers you can reduce the amount of code duplication when doing that!

Installing

yarn install @entria/graphql-mongo-helpers

Right now, the package has two helpers, createMongoConditionsFromFilters and buildSortFromArg . In this post we will look into the first one.

createMongoConditionsFromFilters(filterArg, mapping, context)

The basic idea around this helper, is that if you have a resolver that looks like this:

you can define a mapping for the filter arg:

and inside your resolver do something like that:

If the client supplied the following query:

query ExampleQuery {

users(filter: {

username: "Blah"

age: 19

})

}

filterResult will have the following value:

As you can see, username became a Regex, and age was passed as in, since we have not mapped it.

Fields that are not mapped, are by default treated as having a type of MATCH_1_TO_1 , and a key identical to the passed one.

Operators

You can also use MongoDB comparison operators, you just need to suffix the field name with it in the GraphQL input type. Remember that on the mapping you don’t need to specify the suffix, just the field name, for example, if instead of age: Int we had age_gte: Int , the filterResult above would look like this:

Advanced Filter Types

Besides MATCH_1_TO_1 , there is also AGGREGATE_PIPELINE and CUSTOM_CONDITION , CUSTOM_CONDITION is basically a MATCH_1_TO_1 , but with the format function being required and used to return some conditions that will be merged into the resulting object.

For instance, the following:

would add the $or to the final conditions object.

Note: If you want the client to specify OR conditions like above, there is also support for that:

AGGREGATE_PIPELINE

In case your filter depends on some data that is only available via MongoDB Aggregation Pipeline, this is the type you want to use:

From the above example it’s possible to see that we can combine both types together.