cameronmC
Convex Community5mo ago
3 replies
cameronm

IN operator equivalent?

Is there a way to do an IN operation when querying from an array of values? What's the most efficient/recommended way?

This is what I am currently doing, but just wondering if there is a better way

export const getReports = query({
    args: {
        date: v.string(),
        regionIds: v.array(v.id('regions')),
        propertyTypeIds: v.array(v.id('propertyTypes'))
    },
    handler: async (ctx, args) => {
        // Generate all combinations and query each using the full index
        const allQueries = [];

        for (const regionId of args.regionIds) {
            for (const propertyTypeId of args.propertyTypeIds) {
                allQueries.push(
                    ctx.db
                        .query('reportsResidentialSales')
                        .withIndex('by_date_region_propertyType', (q) =>
                            q.eq('date', args.date).eq('regionId', regionId).eq('propertyTypeId', propertyTypeId)
                        )
                        .collect()
                );
            }
        }

        // Execute all queries in parallel
        const results = await Promise.all(allQueries);

        // Flatten the results
        return results.flat();
    }
});
Was this page helpful?