#default value in schema validator
4 messages · Page 1 of 1 (latest)
Hi @novel drift. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Convex doesn't directly support default values in schema validators, but there are several approaches you can use to handle default values for union types:
Option 1: Use optional fields with default values in your code
When reading the data, you can provide a default value:
// When reading the data
const sortOrder = document.sortOrder ?? "asc";
This is mentioned in the Convex documentation as a common pattern when evolving schemas over time:
// In your schema
sortOrder: v.optional(v.union(v.literal("asc"), v.literal("desc")))
Stack: Ents - Default field values shows this approach.
Option 2: Use Convex Ents (if you're using that library)
If you're using Convex Ents, you can define default values more directly:
// schema.ts with Convex Ents
posts: defineEnt({
// ... other fields
})
.field(
"sortOrder",
v.union(v.literal("asc"), v.literal("desc")),
{ default: "asc" }
)
Option 3: Define reusable validators with helper functions
You can create a helper function that both defines the validator and provides a default value:
// Define a reusable validator with default
export const sortOrderValidator = v.union(v.literal("asc"), v.literal("desc"));
export const defaultSortOrder = "asc";
// In your query function
export const listItems = query({
args: {
sortOrder: v.optional(sortOrderValidator),
},
handler: async (ctx, args) => {
const sortOrder = args.sortOrder ?? defaultSortOrder;
// Use sortOrder here
},
});
This approach is aligned with the pattern described in Stack: Types Cookbook where you define and export validators to keep them consistent across your codebase.