#unset / delete a column

1 messages · Page 1 of 1 (latest)

daring mantle
#

if (suspensionNote) {
await ctx.runMutation(api.users.updateUser, {
id: user._id,
suspensionNote,
status: 'suspended',
});
} else {
await ctx.runMutation(api.users.updateUser, {
id: user._id,
status: 'active',
suspensionNote: undefined,
});
}

suspensionNote is still visible on the db but I already set as undefined

deft flameBOT
#

Hi @daring mantle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

undefined is stripped out of Convex function arguments, so what reaches your mutation is effectively:

// args from client
{ id, status: "active" } // suspensionNote is gone

Because of that, if your mutation does:

export const updateUser = mutation({
  args: v.object({
    id: v.id("users"),
    status: v.string(),
    suspensionNote: v.optional(v.string()),
  }),
  handler: async (ctx, { id, ...args }) => {
    await ctx.db.patch("users", id, args);
  },
});

then ctx.db.patch never sees suspensionNote: undefined, so it leaves the field unchanged. [Working with undefined]

To actually remove the field you must construct the patch object inside the mutation, not on the client:

export const updateUser = mutation({
  args: v.object({
    id: v.id("users"),
    status: v.string(),
    // note: no need to send suspensionNote from client when clearing
    suspensionNote: v.optional(v.string()),
  }),
  handler: async (ctx, { id, status, suspensionNote }) => {
    const patch: any = { status };

    if (suspensionNote !== undefined) {
      // set/update note
      patch.suspensionNote = suspensionNote;
    } else {
      // explicitly remove note
      patch.suspensionNote = undefined;
    }

    await ctx.db.patch("users", id, patch);
  },
});

ctx.db.patch(..., { suspensionNote: undefined }) will remove the field from the document. [Writing data; patch API]

#

Alternatively, you can define two separate mutations: one that sets suspensionNote, and one that clears it with a hard-coded patch({ suspensionNote: undefined }) on the server.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: