#Issue with Zod default

3 messages · Page 1 of 1 (latest)

true charmBOT
#

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

#

The knowledge sources don’t explicitly describe this exact behavior with .default() on Zod booleans inside content collection schemas, so the following is based on how the Content Collections API and schemas are described, but there is no direct confirmation of your specific case in the docs. [Defining schema]

From the docs we know:

  • schema is a Zod object that defines and validates the shape of data for each entry. [Content API]
  • getCollection('tags') returns entries whose data object is the result of that schema. [getCollection; Querying]

However, the docs do not state whether Zod .default() values are always materialized into the resulting data object when the field is absent in the source frontmatter, or whether defaults are only applied at parse time in some situations.

Because of that, I can’t confidently say why your unlisted default is not appearing in tag.data for entries that omit it; the behavior you’re seeing (only explicitly-set values present) is not clearly documented one way or the other.

What is documented and reliable is:

#
  • Every property you want to rely on should be defined in the schema, and you can treat data as matching that schema at the type level. [Defining schema]
  • If you need a guaranteed boolean at runtime, you can:
    • Make the field required in the schema (z.boolean()) and set it explicitly in all frontmatter, or
    • Treat it as optional and coerce in your own code (e.g. const unlisted = tag.data.unlisted ?? false).

Since the docs don’t clarify default materialization, the safest approach within documented behavior is to either:

  1. Set unlisted explicitly in all tag frontmatter, or
  2. Keep it optional in the schema and handle the default yourself when reading tag.data.

If you need to rely on .default(false) being present in data for missing fields, that behavior is not guaranteed or described in the current documentation.

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