How to Query Content Collection in Astro: Simple Guide
In Astro, you query a content collection using the
getCollection function from astro:content. This function fetches all entries from a named collection, which you can then filter or map in your component.Syntax
The main function to query content collections in Astro is getCollection. You import it from astro:content and call it with the collection name as a string.
Example parts:
import { getCollection }- imports the functionawait getCollection('collectionName')- fetches all entries from the collection- The result is an array of content entries you can use in your component
typescript
import { getCollection } from 'astro:content'; const entries = await getCollection('collectionName');
Example
This example shows how to query a collection named blog and list the titles of all blog posts.
typescript
import { getCollection } from 'astro:content'; export async function get() { const blogPosts = await getCollection('blog'); return { body: JSON.stringify(blogPosts.map(post => post.data.title)) }; }
Output
["First Post","Another Post","Learning Astro"]
Common Pitfalls
Common mistakes when querying content collections include:
- Using the wrong collection name string, which returns an empty array.
- Not awaiting
getCollection, causing unresolved promises. - Trying to access data before the collection is loaded.
- Forgetting to export the function as
asyncwhen usingawait.
Always check your collection folder name matches the string you pass.
typescript
/* Wrong: missing await and wrong collection name */ import { getCollection } from 'astro:content'; const posts = getCollection('blogs'); // typo: should be 'blog' console.log(posts); // Promise, not data /* Right: */ import { getCollection } from 'astro:content'; async function loadPosts() { const posts = await getCollection('blog'); console.log(posts); } loadPosts();
Quick Reference
Summary tips for querying content collections in Astro:
- Use
getCollection('name')to fetch all entries. - Always
awaitthe function inside anasynccontext. - Access entry data via
entry.dataand content viaentry.body. - Filter or sort the array as needed after fetching.
Key Takeaways
Use getCollection from astro:content to fetch content entries by collection name.
Always await getCollection inside an async function to get the data array.
Ensure the collection name matches your content folder exactly.
Access content data via the data property on each entry.
Filter or map the results after fetching to use in your component.