Mathias
Mathias11mo ago

How to query and filter with multiple arguments?

I'm trying to query workspaceMembers, where both userId and workspaceId are true. I tried below but it returned null:
const getWorkspaceMemberItem = await ctx.db
.query("workspaceMembers")
.filter((q) =>
q.and(
q.eq("userId", args.userId),
q.eq("workspaceId", args.workspaceId)
)
)
.first()
const getWorkspaceMemberItem = await ctx.db
.query("workspaceMembers")
.filter((q) =>
q.and(
q.eq("userId", args.userId),
q.eq("workspaceId", args.workspaceId)
)
)
.first()
I also tried with withIndex but it seems you can only use one. What is a good way to query with multiple arguments for filtering or indexing? Update: I got the following to work for my use case, but I'm still not sure if that is the most efficient or correct way to do it:
const workspaceMembers = await ctx.db
.query("workspaceMembers")
.withIndex("by_userId", (q) => q.eq("userId", args.userId))
.collect()

const getWorkspaceMemberItem = workspaceMembers.find(
(member) => member.workspaceId === args.workspaceId
)
const workspaceMembers = await ctx.db
.query("workspaceMembers")
.withIndex("by_userId", (q) => q.eq("userId", args.userId))
.collect()

const getWorkspaceMemberItem = workspaceMembers.find(
(member) => member.workspaceId === args.workspaceId
)
2 Replies
sshader
sshader11mo ago
I believe for the .filter you want q.eq(q.field("userId"), arg.userId) (and the same for workspaceId. The code snippet you pasted is checking if arg.userId equals the "userId" instead of checking the field. You can define an index like .index("by_userId_workspace_id", ["userId", "workspaceId"]) and query it with something like .withIndex("by_userId_workspace_id", q => q.eq("userId", args.userId).eq("workspaceId", args.workspaceId)
Mathias
MathiasOP11mo ago
@sshader You are brilliant. Thank you!

Did you find this page helpful?