vis
vis2w ago

is there a way to set default values in

is there a way to set default values in the schema without using literals? e.g. i want set a boolean field to false by default
3 Replies
erquhart
erquhart2w ago
The general approach is: - Make a single helper function (not a Convex function) that is responsible for committing inserts to the table in question (I have one for all my tables) - In that function, set the value of the field to false if no value is provided Ah I see someone already responded with this
vis
visOP2w ago
may i see your function, or like a simplified version of it pls
erquhart
erquhart2w ago
Something like:
// convex/db/posts.ts

// Schema for example purposes, doesn't have to be colocated
export const schema = defineTable({
title: v.string(),
date: v.string(),
isPublished: v.boolean(),
})

export const insertPost = (
ctx: MutationCtx,
input: {
title: string,
date?: string,
}
) => {
return ctx.db.insert('posts', {
title: input.title,
date: input.date || new Date().toString(),
isPublished: false
})
}

// Now this
ctx.db.insert('posts', input)

// Becomes this
insertPost(ctx, input)
// convex/db/posts.ts

// Schema for example purposes, doesn't have to be colocated
export const schema = defineTable({
title: v.string(),
date: v.string(),
isPublished: v.boolean(),
})

export const insertPost = (
ctx: MutationCtx,
input: {
title: string,
date?: string,
}
) => {
return ctx.db.insert('posts', {
title: input.title,
date: input.date || new Date().toString(),
isPublished: false
})
}

// Now this
ctx.db.insert('posts', input)

// Becomes this
insertPost(ctx, input)

Did you find this page helpful?