Gorka Cesium
Gorka Cesium2y ago

union kind

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(),
})
)
);
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,
})
)
});
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,
})
)
});
Schemas | Convex Developer Hub
Schema validation keeps your Convex data neat and tidy. It also gives you end-to-end TypeScript type safety!
5 Replies
Michal Srb
Michal Srb2y ago
Both should work totally fine! Give it a try and let us know if you run into any problems.
Gorka Cesium
Gorka CesiumOP2y ago
is there an example of how to patch a table with a union like this?
Nicolas
Nicolas2y ago
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 },
});
// ✅
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 },
});
// ❌
db.patch(id, {
value: { width: 100 },
});
// ❌
Gorka Cesium
Gorka CesiumOP2y ago
Got it, thanks I got it to work 👌
Nicolas
Nicolas2y ago
Glad to hear this!

Did you find this page helpful?