Mikael Lirbank
Mikael Lirbank17mo ago

I think I know the answer to this but I

I think I know the answer to this, but I want to make sure. Consider this schema:
threads: defineTable({
title: v.optional(v.string()),
memberIds: v.array(v.id("users")),
isClosed: v.boolean(),
}).index("is_closed", ["isClosed"]),
threads: defineTable({
title: v.optional(v.string()),
memberIds: v.array(v.id("users")),
isClosed: v.boolean(),
}).index("is_closed", ["isClosed"]),
There is no way to query for all threads where a certain users._id is a member?
9 Replies
nipunn
nipunn17mo ago
With this data model, there's not a way. One strategy is to have a separate table for thread members
thread_members: defineTable({
memberId: v.id("users"),
threadId: v.id("threads"),
})
thread_members: defineTable({
memberId: v.id("users"),
threadId: v.id("threads"),
})
That way you can index on memberId or threadId
lee
lee17mo ago
if you want something easy & inefficient, you can do the filter in javascript -- do a .query('threads').collect() and then filter on the returned array
Mikael Lirbank
Mikael LirbankOP17mo ago
Thanks! This is the approach we are implementing. Just wanted to be sure before we change the schema 🙏
nipunn
nipunn17mo ago
Another advantage of the separate table is that it's easy to query for all threads for a member (in case you want to show that in one of your views) as well as all members for a thread.
天翔
天翔17mo ago
What about helpers from convex? He might use this one as well I mean asyncmap
Mikael Lirbank
Mikael LirbankOP17mo ago
That will probably get out of hand pretty soon in production...
lee
lee17mo ago
Functional 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.
nipunn
nipunn17mo ago
Convex actually internally uses something similar for team_member - since you can be on more than one team and teams can have more than one member! Same idea.
Mikael Lirbank
Mikael LirbankOP17mo ago
Thanks a bunch everyone, this is super helpful! I haven't read the helpers article yet, but will that run on the server in a best-practices way? I think I got what I need. Thanks a again good people!

Did you find this page helpful?