DEV Community

Haad Baig
Haad Baig

Posted on • Originally published at Medium on

Dynamic Query Data/Filter Data on Multiple Fields using GraphQL | MongoDB Mongoose

Query/Filter data with multiple fields using GraphQL is different yet a very interesting task. Filtering through database has always been a simple yet tricky task. And when filtering includes multiple fields and data is being fetched using GraphQL, things get really messy. This article will help you in filtering data on multiple fields using GraphQL, MongoDB and Mongoose. In fact we will query data or filter data by sending fields and their values as input. This kind of functionality is usually used in e-commerce websites where we apply multiple filter like color, price, region, reviews etc. on searched data. I will use NestJS to do this task but the method is same for NodeJS and is similarly applicable for JavaScript based platforms. I will attach the GitHub repo link in the end of the article.

**Disclaimer:** I will skip the project creating part to keep the article short and generic for both Nest JS and Node JS, if you are new to NestJS you can see the start of my previous articles where I have mentioned the method to create a project using Nest CLI, I'll mention the link at end.  
Enter fullscreen mode Exit fullscreen mode

Codebase Explanation:

Here I am using a scenario where we have a database of users and mobile phones. We need to find all the users who have used specific mobile phone. An array with names of mobile-phone’s ids is maintained in user schema and a separate table with Mobile Phones is present in DB.

Method explanation:

We will send data in form of array from GraphQL client. The data will be processed in such a way that the output will be an object of key-value (field_name: value) pair.

Resolver for Fetching Data from GraphQL:

Lets first write a resolver to fetch data by calling GraphQL API from GraphQL client.

For NestJS:

@Query(() => [User], {name: "FindWithMultipleFields"})

findWithMultipleFields (
@Args('fields', { type: () => [String]} ) fields: any,
@Args('values', { type: () => [[String]]} ) values: any) {

return this.userService.findWithMultipleFields(fields, values);

}
Enter fullscreen mode Exit fullscreen mode

For NodeJS:

const resolvers = 
{   
Query: {     
findWithMultipleFields(fields, values) {       
return users.findWithMultipleFields(fields, values);     
}}}
Enter fullscreen mode Exit fullscreen mode

here for Node, we are using JS classes.

Manipulating Data into key-value Pair:

Now this is the main part and it is similar for both Node and Nest because it is basic JavaScript task. Now we have out array of fields and array of values. We need to process it in such a way that the output is an object of {field: value} pairs.

async findWithMultipleFields (fields: any, value: any): Promise<UserDocument[]> {

const result = value.reduce(function(result, field, index) {
result[fields[index]] = field;
return result;
}, {})
return await this.userModel.find(result);

}
Enter fullscreen mode Exit fullscreen mode

This code will work in a following way.

**Input:** 
field : [model, price]
value: ['Iphone', 20000]

**Output:**  
result: {{model: 'Iphone', price: 20000}} 
Enter fullscreen mode Exit fullscreen mode

Since mongoose find function takes an object of key-value pairs, thus we only have to pass the variable result in Model.find() and we will get the filtered data.

Sending Data from GraphQL:

Here I am attaching a screen shot of GraphQL client to showcase the calling of GraphQL API.

Query Data/Filter Data on Multiple Fields using GraphQL | MongoDB Mongoose

Here I have passed data in the form of array, even though I am querying on single field here but you can test it and it will for sure work on multiple fields. Output can be seen on the right side of the screenshot attached.

Here is the linkto the final code base, a dummy project that I made to implement this use-case for you.

GitHub - haadbaig/NestJS-concepts at multiple-field-query-gql

Conclusion:

I hope this was useful for you. Querying data from database by filtering on multiple fields is an important simple yet a tricky task, and when GraphQL is added in the stack, it become more tricky, however, I believe that after reading this article it will become understandingly easy for you.

If you liked my writing, and find it helpful, do share it with you fellows and leave a comment and claps for me. Also connect me on my LinkedIn profile.

You can also read my previous article on uploading files with GraphQL mutations, here is the link:

Uploading files using GraphQL Client to MongoDB with NestJS / NodeJS

Top comments (0)