'Retrieve all products with same metadata value in Stripe

In Stripe (using Next.js and Node.js), I'm trying to retrieve all products with the same key-value pair in their metadata:

example: retrieve all products with metadata: {category: 'foo'}

In attempts to render category-specific pages, I don't want to list and parse through my whole catalog but I also know that products can only be retrieved through id (docs), inferring that I would have to:

list all products 
for all products:
  if metadata matches, 
    add id to array
for id array:
  retrieve each

This is brute forcing though, and not a good idea.

What would be the best way to retrieve conditionally based on metadata?

Any help is appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source