codebird
codebird3mo ago

Document IDs | Convex Developer Hub

Hi, 1. Can someone explain the difference between userID, _id and Id? 2. Is the userId same as _id? or does each userId has a different _id? 3. Also, the docs mention that we need to mention Id<"tasks" like const task = useQuery(api.tasks.getTask, { taskId: id as Id<"tasks"> }) to ensure that the ID belongs to the expected table, but haven’t we already declared the expected table beforehand in the query itself- “api.tasks.getTask”, so why do we need this { taskId: id as Id<"tasks"> } syntax? Reference- https://docs.convex.dev/database/document-ids
Document IDs | Convex Developer Hub
Create complex, relational data models using IDs.
5 Replies
Indy
Indy3mo ago
1. in that document userId is the return value of the insert function call. That returns the new id of that row in Convex. This the value that shows up in the _id field in the users table. Id is the TypeScript type of this value. 2. the userId is the same as the value of the _id field.
Indy
Indy3mo ago
3. The example you're referring to is getting an id as a string from local storage on the browser (not on the cloud). TypeScript does not know the type of this id so you have to cast it using the as modifier.
Document IDs | Convex Developer Hub
Create complex, relational data models using IDs.
Indy
Indy3mo ago
Hope this helps. There are three distinct things to think about: 1. the actual value (what's stored in userId in the example) 2. The name of the column where Convex stores the id for the table _id 3. and the TypeScript type: Id<"users">
codebird
codebirdOP3mo ago
Kindly confirm the following interpretation: So an id will be automatically generated whenever a new insert happens, whether we assign the value to userId or not. And if we don’t assign, a new column in the table will be automatically created under the heading '_id'. Example- 1. Sample userId: “abcd1234” 2. RetrievedUser: { _id: "abcd1234", name: "Michael Jordan"} 3. And finally for { const userId = retrievedUser._id} we would get "abcd1234”. So the userId is the same as the value of the _id field. Also, in this example- //app.tsx const task = useQuery(api.tasks.getTask, { taskId: id as Id<"tasks"> }); //convex/tasks.ts export const getTask = query({ args: { taskId: v.id("tasks"), } So the v.id mentioned here refers to the automatically generated '_id' in the tasks table?
Indy
Indy3mo ago
Two bits of clarification, to be super duper explicit: 1. You can't actually write to the _id field. These are generated by Convex. So you can't set "userId" that's just the name of the variable of the return value from the insert. the insert function always returns the Convex generated value for the _id field for that document. 2. v.id is a convex validator. That bit of the code tells convex that when it gets the argument taskId for the getTask query function, that it will be a valid Id type. This is something Convex enforces at runtime.

Did you find this page helpful?