dannyelo
dannyelo5mo ago

Query organizations that belong to one user

Hello, I'm trying to query multiple organizations a user is assigned. Here I share my code. Is this the best way to make this types of queries? Thanks! schema.ts
organizations: defineTable({
legal_name: v.string(),
support_email: v.string(),
phone: v.string(),
}),
organization_users: defineTable({
userId: v.string(), // clerk user id
organizationId: v.id("organizations"),
role: v.string(),
}),
organizations: defineTable({
legal_name: v.string(),
support_email: v.string(),
phone: v.string(),
}),
organization_users: defineTable({
userId: v.string(), // clerk user id
organizationId: v.id("organizations"),
role: v.string(),
}),
organizations.ts
export const getUserOrganizations = query({
args: {
userId: v.string(), // clerk user id
},
handler: async (ctx, args) => {
// Get user organizations ids
const userOrgs = await ctx.db
.query("organization_users")
.filter((q) => q.eq(q.field("userId"), args.userId))
.collect();
const organizationsIds = userOrgs.map((org) => org.organizationId);

const organizations = await ctx.db.query('organizations').filter((q) => q.) // I'm stuck here...
return organizations;
},
});
export const getUserOrganizations = query({
args: {
userId: v.string(), // clerk user id
},
handler: async (ctx, args) => {
// Get user organizations ids
const userOrgs = await ctx.db
.query("organization_users")
.filter((q) => q.eq(q.field("userId"), args.userId))
.collect();
const organizationsIds = userOrgs.map((org) => org.organizationId);

const organizations = await ctx.db.query('organizations').filter((q) => q.) // I'm stuck here...
return organizations;
},
});
1 Reply
dannyelo
dannyeloOP5mo ago
Found the solution
export const getUserOrganizations = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const userOrgs = await ctx.db
.query("organization_users")
.filter((q) => q.eq(q.field("userId"), args.userId))
.collect();
const organizationsIds = userOrgs.map((org) => org.organizationId);

const organizations = await Promise.all(
organizationsIds.map(async (id) => {
return await ctx.db.get(id);
})
);

return organizations;
},
});
export const getUserOrganizations = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const userOrgs = await ctx.db
.query("organization_users")
.filter((q) => q.eq(q.field("userId"), args.userId))
.collect();
const organizationsIds = userOrgs.map((org) => org.organizationId);

const organizations = await Promise.all(
organizationsIds.map(async (id) => {
return await ctx.db.get(id);
})
);

return organizations;
},
});

Did you find this page helpful?