#union kind

6 messages · Page 1 of 1 (latest)

bitter finch
#

https://docs.convex.dev/database/schemas#unions

example from the docs

defineTable(
  v.union(
    v.object({
      kind: v.literal("StringDocument"),
      value: v.string(),
    }),
    v.object({
      kind: v.literal("NumberDocument"),
      value: v.number(),
    })
  )
);

in this example I wonder if value can be a v.object instead of v.string and v.number.

I also wonder if the kind field has to be always named kind or can it be also tag?

I'm exploring how to map this to Rescript Variants

I would like to do something like this


let jobWindow = {
  width: v.number(),
  height: v.number()
}
let jobProduct = {
  qty: v.number(),
  name: v.string()
}
defineTable({
 v.union(
    v.object({
      tag: v.literal("JobWindow"),
      value: jobWindow,
    }),
    v.object({
      tag: v.literal("JobProduct"),
      value: jobProduct,
    })
  )
});

Schema validation keeps your Convex data neat and tidy. It also gives you end-to-end TypeScript type safety!

silent nebula
#

Both should work totally fine! Give it a try and let us know if you run into any problems.

bitter finch
#

is there an example of how to patch a table with a union like this?

robust grove
# bitter finch is there an example of how to patch a table with a union like this?

When you patch a document that has a union schema, the same rules apply as when you’re using regular documents. Just keep in mind that since you’re using object fields in your last example, the whole object field will be replaced by db.patch.

For instance, you can do this on a document that has tag JobWindow:

db.patch(id, {
  value: { width: 100, height: 200 },
});
// ✅ 

But this won’t work, because it will try to remove the height field from the object:

db.patch(id, {
  value: { width: 100 },
});
// ❌
bitter finch
#

Got it, thanks

#

I got it to work 👌