Query documents using where filter on field populated with beforeRead hook

discord user avatar
Payload Team
9 months ago

@svnx 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 ^

  • default discord avatar
    9 months ago

    @jesschow 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


    array using built-in


    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


    is always


    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


    boolean than multiple conditions)

    I started with the


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

    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)

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!


Connect with the Payload Community on Discord



Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.