Aggregate function

default discord avatar
eloahsam
2 months ago
3

i created a "AfterRead" in a table called Categories that gets the number of Places with a specific category , the function use to work im not sure why it doesnt now , this is the function



const get = (url, params = {}) => {


const query: any = qs.stringify(params, { addQueryPrefix: true });


console.log(

${url}${query}

);


return fetch(

${url}${query}

);


};


export const queryRelations: any = async (data, route) => {


const request = await get(payload.getAdminURL() + route, {


where: {


// the 'in' operator is used when relations can be more than one


category: { in: data.id },


// to add more query constraints use 'or', 'and' operator objects


},


});



const result: any = await request;


if (result?.docs) {


return result?.totalDocs;


}



if (result.status >= 400) {


return console.error();


}


return 0;


};

  • discord user avatar
    Jarrod
    Payload Team
    last month

    Sounds like exactly what @jesschow describes in this post about virtual fields:

    https://twitter.com/payloadcms/status/1645759920761962496?s=20

    Give that a watch. In your afterRead hook you can use the local api instead of REST because afterRead hooks only run on the server.



    Here is something I just threw together that I think is what you are looking for:



    {
      name: 'categoryCount',
      type: 'number',
      hooks: {
        beforeChange: [
          ({ siblingData }) => {
            siblingData.categoryCount = undefined;
          },
        ],
        afterRead: [
          async ({ req, originalDoc }) => {
            const docQuery = await req.payload.find({
              collection: 'places',
              where: {
                categories: {
                  in: [originalDoc.id],
                },
              },
            });
    
            return docQuery.totalDocs;
          },
        ],
      },
    }
  • default discord avatar
    eloahsam
    last month

    yeah im using that now but created a reusable function for future case if another table needs it



    export const queryRelations: any = async (data) => {
      const experiences = await payload.find({
        collection: "experiences",
        where: {
          // the 'in' operator is used when relations can be more than one
          category: { equals: data.id },
          // to add more query constraints use 'or', 'and' operator objects
        },
        depth: 0,
        limit: 0,
      });
    
      if (experiences?.docs) {
        return experiences?.totalDocs;
      }
    
      return 0;
    };
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.