A company has many users, but a user
A company has many users, but a user only has one company. (one2many)
Here is my schema:
import { defineSchema, defineTable } from "convex/server"
import { Infer, v } from "convex/values"
export const roleValidation = v.union(
v.literal("DEWA"),
v.literal("ADMIN"),
v.literal("OWNER"),
v.literal("MANAGER"),
v.literal("CASHIER"),
v.literal("USER"),
)
export const companyValidation = v.object({
name: v.string(),
slug: v.optional(v.string()),
phone: v.string(),
logo: v.optional(v.string()),
isPublished: v.boolean(),
location: v.string(),
})
const userValidation = v.object({
clerkUser: v.any(), // this is UserJSON from @clerk/backend
email: v.string(),
role: roleValidation,
firstName: v.union(v.string(), v.null()),
lastName: v.union(v.string(), v.null()),
imageUrl: v.string(),
companyId: v.optional(v.id("companies")),
})
export default defineSchema(
{
companies: defineTable(companyValidation),
users: defineTable(userValidation)
.index("by_clerk_id", ["clerkUser.id"])
.index("email", ["email"])
.index("companyId", ["companyId"]),
},
)
10 Replies
If you need all users returned with the company, what you're doing works (your earlier code seemed to indicate something like this). You can also index the users table on companyId and query the users for a company that way, and use pagination if the list is large.
Yeah, that's what I want to. After collect() if I add dot ".", typescript infers an "include()" method, but I can't find in the documentation of "include()". I'm guessing if it's like as prisma syntax to include the company of each user. Isn't it? Or not?
There's no include method, can you share a screenshot of that?
If you wrap the awaited collect in parentheses, you get an array, and that would have an
includes()
method. Only thing I can think of.
But you'll want to take a look at the docs to better understand Convex in a basic sense, api is different from Prisma.here

I'm gonna read one more time the documentation. Thank you for your response.
that's really odd that it would suggest that,
collect()
returns a promiseDoc on the basics of joins: https://docs.convex.dev/database/reading-data#join
Reading Data | Convex Developer Hub
Query and
It would probably insert parentheses if he accepted the suggestion
@v could you provide the example code using includes() ? or the documentation related to it.
you would have to query all the items with collect. so everything would be loaded into memory
you cant have an includes filter
whats the end goal? or are you just learning
if you wanna get all the users for a company you could have them as a field inside the schema as an array of user ids