0
0
AstroHow-ToBeginner ยท 3 min read

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 function
  • await 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 async when using await.

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 await the function inside an async context.
  • Access entry data via entry.data and content via entry.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.