Reputation: 15647
I am using GraphQL within the GatsbyJs framework.
I have multiple files with JSON data. The structure of data is similar to this:
{
...,
"sections" / "menuSections"
}
That last field can be either 'sections' or 'menuSections' in each file. My current graphQL query looks like this:
{
allDataJson {
nodes {
menuSections
}
}
}
This query returns the correct 'menuSections', however, data-files which do not have 'menuSections' are returned as null
. How can I get GraphQL to only return data from files which contain 'menuSections', i.e. how to return data within which 'menuSections' exist. I am looking for an operator like $exists
.
Upvotes: 4
Views: 6454
Reputation: 11577
if sections
& menuSections are string or arrays of string, maybe you can filter for null
:
{
"menuSections": "..."
}
// query
{
allDataJson(filter: {
menuSections: {
ne: null
}
}) {
nodes {
menuSections
}
}
}
If they are object, you can still filter for null
, but it has to be applied to one of the field inside that object. If your objects don't have a common field, this won't work:
{
"menuSections": {
"menuSectionField": "..."
}
}
// query
{
allDataJson(filter: {
menuSections: {
menuSectionField: {
ne: null
}
}
}) {
nodes {
menuSections
}
}
}
If they are array of objects, you can do the same thing but with elemMatch
:
{
"menuSections": [
{ "menuSectionField": "..." },
{ "other": "..." }
]
}
// query
allDataJson(filter: {
menuSections: {
elemMatch: {
menuSectionField: {
ne: null
}
}
}
}) { ... }
Worst case worst, I think you might be able to define some sort of custom types that ensure existence of menuSections so you can query allDataWithMenuSections
etc., but if filter works it's much simpler.
Upvotes: 2
Reputation: 113
It looks like there isn't an $exists
operator in GraphQL. Instead what you can do is add some logic in the resolver to check if a field is not null. I found two older questions related to yours:
GraphQL query and check the returned data
GraphQL query: only include field if not null
Upvotes: 1