#can we set a default value of a key in convex schema?
4 messages · Page 1 of 1 (latest)
Hi @static grove. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Convex's built-in schema system does not support specifying default values for fields directly in the schema definition. When you add a new field to your schema, the recommended approach is to make it optional (using v.optional), then manually ensure that new documents include the field, and optionally run a migration to backfill existing documents with a default value. After all documents have the field, you can make it required in the schema. This process is described in detail in the Convex documentation and community discussions Stack: Data Migrations using Mutations, Stack: Default field values.
For example, to add a field with a default value:
- Update your schema to make the field optional:
posts: defineTable({ // ... other fields contentType: v.optional(v.union(v.literal("text"), v.literal("video"))) }), - Run a migration to set the default value for existing documents.
- Update your code to always provide the field when creating new documents.
- Change the schema to make the field required.
If you want true default values at the schema level (so that TypeScript enforces the field is always present and defaults are automatically filled), this is not possible with the built-in Convex schema system. However, the Convex Ents library provides a way to specify default values for fields, but this is an additional library and not part of the core Convex schema system Stack: Default field values.
In summary:
- Core Convex schema: No, you cannot set default values directly in the schema.
- With Convex Ents: Yes, you can specify default values, but this requires using the Ents library.