const disclosures = defineCollection({
loader: glob({ pattern: "**/*.json", base: "./src/content/disclosures" }),
schema: z.object({
id: z.number(),
text: z.string()
})
});
const products = defineCollection({
loader: glob({ pattern: "**/*.{md,mdx}", base: "./src/content/products" }),
schema: z.object({
id: z.string(),
title: z.string(),
disclosures: reference('disclosures')
})
});
---
id: sample-id
title: sample title
disclosures: a
---
{JSON.stringify(frontmatter)}
{frontmatter.disclosures.id} \<-- this is undefined
#How can I access the data of a content collection reference?
4 messages · Page 1 of 1 (latest)
Hi @drifting sparrow. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To access the data of a content collection reference, you need to use the getEntry() or getEntries() function, depending on whether you're referencing a single entry or multiple entries. Let me explain how to do this based on the example you provided.
In your case, you have a products collection that references entries from the disclosures collection. Here's how you can access the referenced data:
- First, import the necessary functions:
---
import { getEntry } from 'astro:content';
---
- Then, fetch the product entry and its referenced disclosure:
---
import { getEntry } from 'astro:content';
// Assuming you're in a page that knows the product ID
const product = await getEntry('products', 'sample-id');
const disclosure = await getEntry(product.data.disclosures);
---
Now you can access the disclosure data:
<h1>{product.data.title}</h1>
<p>Disclosure ID: {disclosure.data.id}</p>
<p>Disclosure Text: {disclosure.data.text}</p>
The reason why frontmatter.disclosures.id is undefined in your example is that the reference itself doesn't contain the actual data. It only contains the information needed to fetch the referenced entry.
This approach is described in the Astro documentation Accessing referenced data.
If you're dealing with multiple references (e.g., if disclosures was an array of references), you would use getEntries() instead:
---
import { getEntries } from 'astro:content';
const product = await getEntry('products', 'sample-id');
const disclosures = await getEntries(product.data.disclosures);
---
{disclosures.map(disclosure => (
<p>{disclosure.data.id}: {disclosure.data.text}</p>
))}
Remember that getEntry() and getEntries() are asynchronous functions, so you need to use await when calling them.