Skip to content
Advertisement

Mongoose query where X is in both arrays and where Y is in only one array

I am building a filtering system and I am stuck on a problem, please keep in mind that this is demo code, this is not the same project but the concept is the same, I replaced the names to make it as easily understandable as possible.

I got a filled filter object which gets sent like this (it consists of an array with id’s) – keep this one in mind:

JavaScript

If you would take a look at both the Company and State collections, they would look something like this:

JavaScript

There is also a global collection which combines both of these, this is the collection I’m going to be using:

JavaScript

Now, a company can be nationwide as well as state-oriented (as seen in above collection). So I have a repository like this:

JavaScript

The problem occurs that once I execute the query like this, with the filters at the top:

JavaScript

What the above code basically does, is it adds the items based on if you selected them, in the end you get a query object. The problem there is that it has to be in BOTH arrays. So since "company_a" is nationwide, it shouldn’t be searched in the states array.


To get a clear view of the point, here are some examples of how the system should work:

JavaScript

A solution I can think of is this:

JavaScript

This gives me what I want, however I think this should be able to be completed by the database. Because now I have to do two queries and combine them both, this does not look clean at all.

I hope that I can do this in ONE query to the database. So either the query builder should be fixed or the query itself, I can’t seem to get it working properly..

Advertisement

Answer

All you need to do is built a smarter query with boolean logic, In this case all you want to do is allow a nationwide company to be fetched regardless of the selected states.

Here’s how I would do it:

JavaScript

Now if a state is selected the query is either the state._id is in the selected query OR the company is nationwide.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement