motzM
Convex Community7mo ago
2 replies
motz

Upsert feature

Hi, I'm currently doing the following:
export const setBalance = internalMutation({
    args: {
        minecraftUuid: v.string(),
        balance: v.number(),
    },
    handler: async (ctx, args) => {
        const player = await ctx.db
            .query("players")
            .withIndex("by_minecraft_uuid", (q) =>
                q.eq("minecraftUuid", args.minecraftUuid),
            )
            .unique()
        if (!player) {
            await ctx.db.insert("players", {
                minecraftUuid: args.minecraftUuid,
                balance: args.balance,
            })
            return
        }
        await ctx.db.patch(player._id, {
            balance: args.balance,
        })
    },
})


But I was wondering if there was a simpler way to achieve this UPSERT-like behaviour in Convex? I mean it should be possible to automatically create a new document if none matches, right?

Or could I create my own helper function for that? Anyone have an idea of how to go about doing that?
Was this page helpful?