One Collection Pointing at Another
References
`reference(name)` in a schema declares "this field is an id from the named collection". Astro validates and lets you `getEntry()` the referenced item.
What you'll learn
- Declare a reference field
- Resolve a reference at render time
- Reference arrays
When one collection’s entry needs to point at another — a post’s
author referring to the authors collection — use
reference().
Declaring a Reference
import { defineCollection, reference, z } from "astro:content";
import { glob, file } from "astro/loaders";
const authors = defineCollection({
loader: file("./src/data/authors.json"),
schema: z.object({
id: z.string(),
name: z.string(),
}),
});
const blog = defineCollection({
loader: glob({ pattern: "**/*.md", base: "./src/blog" }),
schema: z.object({
title: z.string(),
author: reference("authors"), // ← must be a valid author id
}),
});
export const collections = { authors, blog }; A post’s frontmatter looks like:
---
title: Hello, Astro
author: ada # must match an entry id in `authors`
--- If author isn’t a real id, the build fails — pointing at the
file.
Resolving the Reference
getEntry accepts a reference object and returns the linked entry:
---
import { getCollection, getEntry } from "astro:content";
const posts = await getCollection("blog");
const post = posts[0];
const author = await getEntry(post.data.author); // pass the reference
---
<h1>{post.data.title}</h1>
<p>by {author.data.name}</p> post.data.author is { collection: "authors", id: "ada" }, and
getEntry accepts that directly.
Reference Arrays
A post might have multiple tags or authors — declare an array of references:
schema: z.object({
title: z.string(),
tags: z.array(reference("tags")),
}), To resolve them all:
---
import { getEntries } from "astro:content";
const tags = await getEntries(post.data.tags);
--- getEntries is getEntry for arrays.
Up Next
Rendering the body of a Markdown / MDX entry.
Rendering Content →