StoicWanderer
StoicWanderer14mo ago

What should I define here, if i want to reference another table by ID?

Hello fellow Convexers, My question is that, because i can't figure it out, what should I put on Line#59, here: https://github.com/andrejmoltok/oceans5/blob/O5T-6-Userlist-Convex-RW/convex/users.ts#L59 if I have defined the table in my schema as is on Line#52 here: https://github.com/andrejmoltok/oceans5/blob/O5T-6-Userlist-Convex-RW/convex/schema.ts#L52 Typescript says it cannot be assigned as string nor viceversa. what comes on line 59 in the users.ts file? Can anyone help please?
GitHub
oceans5/convex/users.ts at O5T-6-Userlist-Convex-RW · andrejmoltok/...
Oceans5 is a BattleShip clone game in Next.js. Contribute to andrejmoltok/oceans5 development by creating an account on GitHub.
GitHub
oceans5/convex/schema.ts at O5T-6-Userlist-Convex-RW · andrejmoltok...
Oceans5 is a BattleShip clone game in Next.js. Contribute to andrejmoltok/oceans5 development by creating an account on GitHub.
4 Replies
ian
ian14mo ago
How is an alliance created? If you create an alliance for every user, you can do something like:
const allianceId = await ctx.db.insert("alliance", {...});
...
return await ctx.db.insert("users", {
...
alliance: allianceId
const allianceId = await ctx.db.insert("alliance", {...});
...
return await ctx.db.insert("users", {
...
alliance: allianceId
However, if an alliance is only created later and users may or may not have one, you might want to define alliance as:
alliance: v.optional(v.id("alliance"))
alliance: v.optional(v.id("alliance"))
in your schema
ian
ian14mo ago
If you might have many alliances for the same user, you might instead do something like not having alliance on the user document, but instead user on the alliances document:
alliance: defineTable({
user: v.id("users"),
//alliance stats
allianceName: v.string(),
...
alliance: defineTable({
user: v.id("users"),
//alliance stats
allianceName: v.string(),
...
where this is a "one to many" relationship, which you can read more about here: https://stack.convex.dev/relationship-structures-let-s-talk-about-schemas#one-to-many
Relationship Structures: Let's Talk About Schemas
In this post we’ll look at some patterns for structuring relationships in the Convex database.
ian
ian14mo ago
Relationship Structures: Let's Talk About Schemas
In this post we’ll look at some patterns for structuring relationships in the Convex database.
StoicWanderer
StoicWandererOP14mo ago
Hey @ian i'm going with setting it with v.optional(), because in my game project the user may or may not be part of an alliance. Thank you for the docs as well.

Did you find this page helpful?