shadow_aya
shadow_aya2y ago

Optional arguments and patch

I read that setting a field to undefined with db.patch unsets it. now I'm a bit afraid of implementing an "update" function that can update any values if you provide a value for them:
export const update = mutation({
args: {
id: v.id("users"),
discordId: v.optional(v.string()),
name: v.optional(v.string()),
email: v.optional(v.string()),
emailVerified: v.optional(v.number()),
image: v.optional(v.string()),
},
async handler(ctx, args) {
return await ctx.db.patch(args.id, {
discordId: args.discordId,
name: args.name,
email: args.email,
emailVerified: args.emailVerified,
image: args.image,
});
},
});
export const update = mutation({
args: {
id: v.id("users"),
discordId: v.optional(v.string()),
name: v.optional(v.string()),
email: v.optional(v.string()),
emailVerified: v.optional(v.number()),
image: v.optional(v.string()),
},
async handler(ctx, args) {
return await ctx.db.patch(args.id, {
discordId: args.discordId,
name: args.name,
email: args.email,
emailVerified: args.emailVerified,
image: args.image,
});
},
});
is this safe if I make the args optional?
3 Replies
Michal Srb
Michal Srb2y ago
In your code example args.email will be unset, so when you try to access it you will get undefined, and so the email would be unset. With patch you probably want ctx.db.patch(id, args) Now the fields that are unset won’t change the document fields in the db.
lee
lee2y ago
^ this but you probably want const {id, ...updates} = args; await ctx.db.patch(id, updates)
shadow_aya
shadow_ayaOP2y ago
oh okay, thanks!

Did you find this page helpful?