#default value in schema validator

4 messages · Page 1 of 1 (latest)

novel drift
#

<@&1228088700710293556> how can i define a default value for a union type validator v.union(v.literal('asc'), v.literal('desc'))

fervent timberBOT
#

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.

#

Remember that when using default values, you'll need to apply them consistently wherever you read the data to ensure consistent behavior throughout your application.

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