#Query documents using where filter on field populated with beforeRead hook

13 messages · Page 1 of 1 (latest)

tawdry cedar
#

@toxic hatch the hooks you are referencing only exist on the collection, for field hooks you can use beforeValidate, beforeChange, afterChange and afterRead.

You can absolutely calculate the field value from a hook - for this scenario, after you query all published articles, map over the articles and return an array containing all the article ids.

#

something like this

const getPublishedArticles: FieldHook = async () => {
  const articles = await payload.find({
    collection: 'articles',
    where: {
      published: {
        equals: true,
      },
    },
  });

  if (articles.docs) {
    return articles.docs.map((doc) => doc.id);
  }

  return null;
};
#

oh I see you're using the REST API, in which case just swap out the payload.find portion with your query ^

toxic hatch
#

@tawdry cedar thanks for the quick reply 🙂 I'm not sure if I understood you correctly. I'll provide some screenshots this time to better describe what I'm trying to achieve. Basically I tried to filter the docs array using built-in where filter on such field:

#

This value is "updated" by beforeRead hook set on the collection:

#

And I tried do something like this:

#

but the docs array will be always empty because published is always false in database

#

and I'm afraid it's just by design and there's nothing I can do about that 😄 I just wanted to make a "dynamic" field to make querying a bit easier (it's simpler to check one calculated published boolean than multiple conditions)

#

I started with the afterRead hook set on field but the behaviour was the same - API filters documents before running hooks

toxic hatch
#

Bump with TLDR;

Is there a simple way to use „where” filter in GraphQL / REST API on virtual field? (virtual field = its value is dynamically calculated using beforeRead hook on collection, example is above)