Shorter unique IDs for documents
is there a recommended way of implemented short code searchable references for documents? for example that I create a Job that would have a
reference
field with value "JD13931" and this value would be unique in the Jobs table. That way the users can search by reference
. This would be to make it easier for users to type in a short ID than the real convex document ids.10 Replies
I would recommend the following:
In your schema:
To look up a job:
To insert a job:
by checking that it exists before inserting it, the ACID transaction guarantees of Convex ensure it'll be unique if the mutation succeeds in inserting it
If you use my helper from this relationship post it can look like
await getOneFrom(db, "jobs", "reference", userInput);
https://stack.convex.dev/functional-relationships-helpers#back-reference-the-getonefrom-helperFunctional Relationships: Helpers
In this post, we’ll look at some helper functions to help write code to traverse relationships in a readable, predictable, and debuggable way.
ah I see, so I could generate the
reference
with a lib like https://github.com/ai/nanoid and then check in a recursive loop with getOneFrom
to see if it exists otherwise keep trying new reference
GitHub
GitHub - ai/nanoid: A tiny (130 bytes), secure, URL-friendly, uniqu...
A tiny (130 bytes), secure, URL-friendly, unique string ID generator for JavaScript - GitHub - ai/nanoid: A tiny (130 bytes), secure, URL-friendly, unique string ID generator for JavaScript
that should work. thanks
I do this in my chess app demo:
https://github.com/xixixao/convex-chess-demo/blob/main/convex/game.ts#L10-L20
(but as @ian pointed out I should be using an index instead of a filter 🙂 )
I was so long into functional programming that i forgot the usefulness of a while loop, thanks for sharing
can this helper functions be in a file outside of the convex folder? otherwise if they live in the convex folder would they be registered as mutations/queries?
Only functions wrapped in query/mutation/action are registered.
But yes can also be anywhere and be imported.
The convex-helpers GitHub repo has a bunch of useful stuff if you haven’t perused before.
ah ok, so makes more sense to have it in convex folder
Yeah, I’ve started storing helpers in convex/lib but anywhere works. Same file if it’s only used there. However you like
GitHub
GitHub - get-convex/convex-helpers: A collection of useful code to ...
A collection of useful code to complement the official packages. - GitHub - get-convex/convex-helpers: A collection of useful code to complement the official packages.