Upsert feature in convex?
HI - is there any plans to introduce a .upsert function in convex?
Currently this is how I'm approaching it:
export const upsertTask = mutation({
args: {
text: v.string(),
},
handler: async (ctx, args) => {
const existingItem = await ctx.db
.query("tasks")
.filter((q) => q.eq(q.field("task_name"), args.text))
.first();
if (existingItem !== null) {
await ctx.db.patch(existingItem._id, {
task_name: args.text,
});
} else {
await ctx.db.insert("tasks", {
task_name: args.text,
isCompleted: false,
});
}
},
});
Which achieves the purporse, but was thinking if there was a better/shorter approach to this?
Thank you
3 Replies
The team can speak to whether there are any internal plans around formal upsert approach, but I can confirm that what you're doing there is how upserts work today. You're doing it right.
I'd only say you could use
.unique()
instead of first()
if you're expecting 0 or 1 matches.If you want it to be more efficient when you have lots of tasks, you can change the
.filter
into a .withIndex
. But otherwise this looks goodThanks. The support here is amazing!