beermanB
Convex Community12mo ago
2 replies
beerman

Type Mismatch in Update Mutation with Optional Fields

I’m running into a type mismatch issue when updating an account using a mutation. Simplified version of my setup:
schema.ts
export const account = v.object({
    name: v.string(),
    type: accountType,
    balance: v.number(),
    totalDeposited: v.number(),
    totalWithdrawn: v.number(),
    profitLoss: v.number(),
    commission: v.number(),
    notes: v.string(),
    isActive: v.boolean()
});

accounts.ts
onst { type, ...updates } = account.fields;

export const update = mutation({
    args: v.object({
        accountId: v.id('accounts'),
        ...updates
    }),
    handler: async (ctx, args) => {
        const { accountId, ...updates } = args;
        await ctx.db.patch(accountId, updates);
    }
});

component
    async function handleUpdateAccount(
        accountId: Id<'accounts'>,
        updates: Partial<Omit<WithoutSystemFields<Doc<'accounts'>>, 'type'>>
    ) {
        await client.mutation(api.accounts.update, {
            accountId,
            ...updates
        });
    }

Error
Types of property 'name' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.

• In the mutation, I’ve excluded the type field and allowed the remaining fields to be updated.
• The handleUpdateAccount function uses Partial so only the fields that need updating are passed.
• I suspect the issue is that the mutation expects all fields to be required, but I’m passing optionals.

Is there a proper way to define the mutation to accept optional fields without manually marking each field as optional? Should I adjust the schema or is there a better solution to handle partial updates?
Was this page helpful?