erquhart
erquhart15mo ago

Creating co-dependent records

- I have tables foo and bar - foo has a required defaultBarId field - bar must have a fooId field I currently have to set foo.defaultBarId to optional, even though it's not, just to serve the split second of the foo record's existence when it doesn't have a defaultBarId. Curious if there's a workaround or a better approach, I'd like to type both fields as required. If there's not something I'm missing here, I'm wondering if ID generation would be possible, as long as the ID is used within the confines of the mutation that it's generated in. In this case I could generate an ID for the bar record first, and then create both records with properly required types.
3 Replies
erquhart
erquhartOP15mo ago
I guess I could also rework my schema and push the circular dependency foreign key to a secondary table for metadata or something. But ideally I'd be able to use tables this way and keep fields required.
sshader
sshader15mo ago
I think what you're doing (setting one of them to be optional / nullable) is the best you can do for now (see https://docs.convex.dev/database/schemas#circular-references) Agree that if we let you generate an ID in a table and create a document with that ID later, this would solve the problem (another shape of solution would be to only enforce the schema at the end of the transaction vs. on every insert, so then you'd only need a type cast in the spot where the field is initially unset, but the schema wouldn't need the optional)
Schemas | Convex Developer Hub
Schema validation keeps your Convex data neat and tidy. It also gives you end-to-end TypeScript type safety!
erquhart
erquhartOP15mo ago
Ooh delaying schema validation is even better, +1

Did you find this page helpful?