Query all users based on an Id
I'm working on optimizing a data query process in our application and could use your insight. Currently, I'm faced with a rather inefficient method of fetching all users associated with a specific group. The process involves multiple steps: initially querying for a user to determine their 'activeGroup' and then using this identifier to fetch the group and its associated users. This approach seems overly cumbersome and I'm convinced there must be a more direct and efficient method.
To give you a clearer picture, here's how our data is structured:
User Document Example:
Group Document Example:
My goal is to simplify this process, ideally querying for all users within a specific group directly, without the preliminary steps currently required. I'm searching for any resources or advice you may have on achieving this more effectively. Do you know of any methods or tools that could facilitate a more streamlined approach to querying these relationships?
Thanks in advance for your help!
6 Replies
I would create a third table of memberships like ({ groupId, memberId }) so you can create the appropriate indexes to make this efficient.
The process would be: in your getAllMembers(groupId) query use an index on group_id to gather all member user ids, then db.get these user ids.
@ballingtOkay that is a good idea! Could you give me an example in code? 🙏
In my description you can see that I have userId (comes from Clerk), which is not the same as the user._id. Would you use user._id instead to get the user doc?
Either one, if you use .userId then you'll want to add an index on that field bit if you use ._id you can use ctx.db.get. Both approaches are efficient.
@Mathias here's a nice article with some code https://stack.convex.dev/relationship-structures-let-s-talk-about-schemas
Relationship Structures: Let's Talk About Schemas
In this post we’ll look at some patterns for structuring relationships in the Convex database.
Thank you a lot! Great help!
@ballingt do you know if it is possible to create a function to get the activeGroupId and then call it within the getGroupMembers function?
My goal is to skip the need to provide the activeGroupId as args. It will clear up my code in the frontend.
If you want to use the active group id of the current user without involving your frontend, you can get the current user object from any convex function. getGroupMembers sounds like a query that accepts a group id and returns the members, so I’d make a separate query for just getting the members for the active group of the current user.