Performance: Defining collections and schemas
This affects page load speed by controlling how content data is structured and validated before rendering, impacting initial data processing and rendering efficiency.
import { defineCollection, z } from 'astro:content'; export const collections = { blog: defineCollection({ schema: z.object({ title: z.string(), date: z.string().transform(str => new Date(str)), author: z.string() }) }) };
import { defineCollection } from 'astro:content'; export const collections = { blog: defineCollection({}) // no schema validation };
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No schema validation | N/A | Multiple reflows possible due to data errors | Higher paint cost from layout shifts | [X] Bad |
| Static schema validation | N/A | Single layout pass with stable data | Lower paint cost with stable layout | [OK] Good |
collection in Astro?title in Astro's collection schema?type and required properties to define fields.title must be a string and required, so { type: 'string', required: true } is correct.const blogSchema = {
title: { type: 'string', required: true },
published: { type: 'boolean', required: false }
};published field?required property of publishedpublished has required: false, so it is optional.published is optional -> Option Dconst projectSchema = {
name: { type: 'string', required: true },
year: { type: 'number', required: true }
};year field. What is the likely cause?year is defined as a number but the content file has it as a string, it causes a type error.year as a string instead of a number -> Option Atitle (string), an optional tags array of strings, and a date that must be a valid ISO date string. Which schema definition is correct?title{ type: 'string', required: true } for title.tags{ type: 'array', items: { type: 'string' }, required: false } to specify an optional array of strings.date as required ISO date string{ type: 'string', format: 'date-time', required: true } to enforce ISO date format.Pass the test and this pattern moves unknown