astrojs

how to retrieve all content with getcollection()


i wanted to add 3 category under /pages folder, each should have paginated data and i also prepared 3 folder in src/content so i can choose category pages from navbar and see paginated results then i click posts and see content.

user will navigate category->paginated category specific posts ->find content

My folder structure like this:

file tree structure

under pages/ folder structure something like this all has own [...page].astro file :

export async function getStaticPaths({paginate}){
    const posts = await getCollection("officer")
    return paginate(posts,{
      pageSize: 1,
    })
};
const {page} =Astro.props;
console.log(page)

[...slug].astro structure something like this:

export async function getStaticPaths(){
    //i want to get all content directory something like below
    //const posts = await getCollection('../content/**/*.mdx'); 
    const posts = await getCollection('engineer');
    return posts.map((entry) => ({
        params: { slug: entry.slug},
        props: {entry},
    }));
};
type Props = {
    entry: CollectionEntry<"engineer">;
}
const {entry} = Astro.props;

When i try to see category pages all works but only i able to get engineer collection because it gets one name and its engineer how to add "eto" and "officer" also?


Solution

  • There’s no built-in utility to get all collections, so you need to do this manually:

    ---
    import { getCollection } from 'astro:content';
    
    export async function getStaticPaths() {
        const engineerPosts = await getCollection('engineer');
        const etoPosts = await getCollection('eto');
        const officerPosts = await getCollection('officer');
        const posts = [...engineerPosts, ...etoPosts, ...officerPosts];
        return posts.map((entry) => ({
            params: { slug: entry.slug },
            props: { entry },
        }));
    }
    
    interface Props {
        entry: CollectionEntry<"engineer" | "eto" | "officer">;
    }
    ---