Query documents using where filter on field populated with beforeRead hook

discord user avatar
jesschow
Payload Team
9 months ago
14

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

    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



    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)



    https://github.com/payloadcms/payload/issues/2398
    image.png
    image.png
    image.png
Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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