Improve documentation around `defineCollection` schema behavior and its impact on query results
Hi Nuxt Content team,
First of all, thank you for your great work on Nuxt Content!
While working with defineCollection and its schema option, I noticed some behavior that might not be immediately intuitive and would benefit from clearer documentation.
Context
When using defineCollection, it's possible to define a custom schema for a collection using zod. This helps ensure type safety for properties defined in frontmatter. For example:
defineCollection({
source: 'blog/*.md',
type: 'page',
schema: z.object({
tags: z.array(z.string()),
image: z.string(),
date: z.date()
})
})
Confusing Behavior
The behavior of queryCollection differs depending on whether a schema is defined or not. For instance, given the following Markdown file:
---
foo: true
bar: false
---
# Hello
And a schema like:
schema: z.object({
foo: z.boolean()
})
Then when accessing the data via queryCollection, the results are:
const data = await queryCollection('docs').path(route.path).first()
data.foo // `true`. defined in schema
data.meta.bar // `false`. not defined in schema
By default, all frontmatter fields are placed under the meta property. However, when a schema is defined, the fields specified in the schema are promoted to the top-level of the returned object. This subtle but important change in structure can be confusing, as it affects how developers need to access the data at runtime.
While the documentation does mention that:
meta: Custom fields not defined in the collection schema https://content.nuxt.com/docs/collections/types
…it may not be immediately obvious that this affects how you access the data at runtime.
Suggestion
I believe this important detail would be more helpful if it were documented directly under the Collection Schema section, with a clear note that fields not included in the schema will be moved to the meta property. This would help developers avoid confusion when switching between schema and non-schema modes.
I'd be happy to contribute a PR for this improvement if the suggestion is acceptable.
Thanks again for all your work on Nuxt Content!
Thanks @odanado for the suggestion. You are more than welcome to drop a PR to improve 🙂
Just to clarify, meta field only exists to prevent losing data. Let's add a note about this field, but highly suggest not to depend on it and instead define fields in the collection's schema.
This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days.
This issue was closed because it has been stalled for 30 days with no activity.