#Do not allow invalid IDs when using reference()
4 messages · Page 1 of 1 (latest)
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()orgetEntries():// if a referenced entry is invalid, this will return undefined. const relatedPosts = await getEntries(blogPost.data.relatedPosts);
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.