Nuxt 3 Content: Filter by Subdirectory Not Working with queryCollection().path()
Hey everyone! 👋
I'm trying to filter content by subdirectory using queryCollection() in Nuxt 3, but it's not working as expected.
📁 My nuxt content folder
❌ The Problem
This returns an empty array, even though files exist:
✅ What I expect:
It should return the product1.yaml and product2.yaml files inside p/cctv.
❓My question:
How can I properly filter a collection by subdirectory using queryCollection()?
2 Replies
Hi @Made Y. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
You're encountering this issue because the
Use
.path()
method in queryCollection()
is designed to match the full, generated route path of a single document (e.g., /p/cctv/product1
), not to filter by subdirectory or prefix. When you use .path('p/cctv')
, it looks for a document whose path is exactly p/cctv
, which doesn't exist—hence, you get an empty array.
To filter all items within a subdirectory, you should use the .where()
method with the LIKE
operator to match all paths that start with your subdirectory. For your case, you want all products under p/cctv/
, so you can do:
- The path
field contains the generated route path (with a leading slash).
- The LIKE
operator with /p/cctv/%
will match all documents whose path starts with /p/cctv/
.
This approach is documented in the migration guide and the queryCollection API docs, which show how to use .where('path', 'LIKE', '/subdir%')
for subdirectory filtering, rather than .path()
which is for exact matches only Converting queryContent to queryCollections | queryCollection API.
Summary:Use
.where('path', 'LIKE', '/p/cctv/%')
to filter by subdirectory, not .path('p/cctv')
.
Let me know if you need an example for a different structure!
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@213866895806300161> Kapa.ai is still learning and improving, please let me know how I did by reacting below.