#Do not allow invalid IDs when using reference()

4 messages · Page 1 of 1 (latest)

pliant bolt
#

When I define a property with reference() in my content collection schema, I don't want to accept invalid IDs. The server should error when the property contains IDs that aren't valid entries in the referenced collection.

severe sageBOT
#

Hi @pliant bolt. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Astro’s current behavior with the reference() function in content collection schemas is to transform the referenced value into an object with collection and id keys. However, validation of whether the referenced ID actually exists in the target collection does not happen at schema validation time. Instead, this check occurs at runtime when you query the referenced entry using getEntry() or getEntries(). If the referenced ID is invalid (i.e., it does not exist in the referenced collection), the query will return undefined, but the server will not throw an error during the initial schema validation or build process.

For example, from the documentation:

Validation of referenced entries happens at runtime when using getEntry() or getEntries():

// if a referenced entry is invalid, this will return undefined.
const relatedPosts = await getEntries(blogPost.data.relatedPosts);

Imports from astro:content

This means that invalid IDs in references do not cause a schema or build error; instead, you must handle the possibility of undefined results in your code. There is currently no built-in way to make the server error immediately when a property contains IDs that aren't valid entries in the referenced collection.

If you need stricter validation, you would have to implement additional checks yourself after querying, or handle the undefined case as an error in your application logic.

#

Summary:
Astro does not error at schema validation or build time for invalid IDs in reference() properties. The check is deferred to runtime, and you must handle missing references in your code. There is no built-in option to enforce this stricter behavior at the schema level according to the current documentation.
Defining collection references | Accessing referenced data

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: