Limit how much values fit into an array
I found no way to limit the amount of values fit into an array, so I open this as a feature request.
I need something that matches this SQL implementation:
10 Replies
interesting. you can just check in the mutation, right?
if (doc.arrayField.length < 3) { db.patch(..) }
yes, that would be a solution.
But it would be nicer to have immediately a type-error if there is the possibility that we insert too many (like we get a type error for the wrong type etc.)
So that it can't happen in the first place that you insert to much items in an array
This could be implemented with tuples and that stuff right?
The general recommendation for more complex validation is to use something like Zod, there's a guide for integrating Zod into your schema here: https://stack.convex.dev/typescript-zod-function-validation
Zod with TypeScript for Server-side Validation and End-to-End Types
Use Zod with TypeScript for argument validation on your server functions allows you to both protect against invalid data, and define TypeScript types ...
I don't want to validate function arguments. I want to limit how much data can fit into my database. for example if I have a v.array() field in my db I want to limit how much can fit into this array
Oh are schemas not covered in that article
in SQL it would be:
You can use Zod for advanced schema validation, there are helpers for it, finding now
ok
A lot of good stuff from the team here, including some info from Ian about extending Zod/Convex usage to schema definition: https://discord.com/channels/1019350475847499849/1186112627462647819
Also includes a breakdown from Jamie on why validation is limited currently
Assuming you control the writes (not a snapshot import or manually editing in the dashboard) I would put the checks and/or type constraints in a function where you update the value. You could have a function that takes in a tuple and inserts/updates the document, or a runtime check if the API is more about appending. That way you have more control over the validation. The costraint in SQL is only useful since you might be trying to append and not having transactional guarantees about its current length