DeepakDahiya
DeepakDahiya5mo ago

Default field value

Is there any way to specify default value for a document field (column)
3 Replies
Heath
Heath5mo ago
Convex Ents have a mechanism for this. But afaik in the vanilla convex there isn’t. They have some documentation talking about reasons why, I think close to the docs regarding migrations. https://labs.convex.dev/convex-ents/schema#field-defaults
Ent Schema - Convex Ents
Relations, default values, unique fields and more for Convex
erquhart
erquhart5mo ago
Welcome! The default answer to most "how do you do X in Convex" is to just code it yourself. The fact that Convex enables this is itself a feature. More and more things will be enabled through packaged solutions, some of which will be "first party", but those too will just be Typescript that a user could write themselves. For default field values, the approach is the same as any default value in JS/TS. Here's an example where a table of posts has a required featured field, and false is provided as the default value in the mutation:
const posts = defineTable({
authorId: v.id('users'),
content: v.string(),
featured: v.boolean(),
})

const insertPost = mutation({
args: {
authorId: v.id('users'),
content: v.string(),
featured: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
const post = {
authorId: args.authorId,
content: args.content,
featured: args.featured ?? false,
}
await ctx.db.insert('posts', post)
},
})
const posts = defineTable({
authorId: v.id('users'),
content: v.string(),
featured: v.boolean(),
})

const insertPost = mutation({
args: {
authorId: v.id('users'),
content: v.string(),
featured: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
const post = {
authorId: args.authorId,
content: args.content,
featured: args.featured ?? false,
}
await ctx.db.insert('posts', post)
},
})
DeepakDahiya
DeepakDahiyaOP4mo ago
I see,
"The default answer to most 'how do you do X in Convex' is to just code it yourself."
Well this, surely helps in building the mental model while using convex. Thanks man!

Did you find this page helpful?