Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Query documents using where filter on field populated with beforeRead hook

default discord avatar
jessrynkar2 years ago
1
@545926768327131137

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
    svn__2 years ago
    @854377910689202256

    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
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.