randy.glasgow
randy.glasgow16mo ago

Querying for records with an array field that contains a value

Im writing a query to return a users available projects they are a member of. How can i query the DB and check that the user_id is in the array i am comparing? I have provided the query so far and the project schema.
No description
No description
2 Replies
ballingt
ballingt16mo ago
There's no "contains" operator on arrays in the query builder so the first thing I'd do is these into memory in your Convex query and then filter them:
export const getProjectsForuserId = query({
...
handler: async (ctx, args) => {
validateIdentity(ctx);
const projects = ctx.db.query("projects").collect();
return projects.filter(p => p.members.includes(args.user_id));
}
});
export const getProjectsForuserId = query({
...
handler: async (ctx, args) => {
validateIdentity(ctx);
const projects = ctx.db.query("projects").collect();
return projects.filter(p => p.members.includes(args.user_id));
}
});
The next thing if there were performance issues here (say once you're productionizing or once you have more than a few thousand projects) is create a "join table" with these associations in it; then this is something that can be done efficiently with indexes.
randy.glasgow
randy.glasgowOP16mo ago
Thank you

Did you find this page helpful?