KenniK
Convex Community14mo ago
3 replies
Kenni

How to query items where array field contains a specific value?

I have a paginated query where I need to filter items based on whether an array field contains a specific category ID. Currently, my query only returns items where the array exactly matches [categoryId], but I need it to return items where categoryId is one of potentially many elements in the array.

Here's my current query:

const baseQuery = ctx.db
    .query("items")
    .withIndex("by_owner_and_categories_and_timestamp", q =>
        q.eq("ownerId", args.ownerId)
        .eq("categories", [args.categoryId])  // Only matches exact array [categoryId]
        .lt("timestamp", Number.MAX_SAFE_INTEGER)
    )
    .order("desc");


For example, if I have these items in my database:
// Item 1 - Currently NOT returned, but I want it to be
{
    ownerId: "owner1",
    categories: ["category1", "category2"],
    timestamp: 123
}

// Item 2 - Currently returned
{
    ownerId: "owner1",
    categories: ["category1"],
    timestamp: 456
}


When querying for categoryId: "category1", I want both items to be returned since they both contain "category1" in their categories array.

Is there a way to achieve this kind of "contains" functionality for array fields in Convex? I need this to work with pagination too.

Any suggestions would be appreciated!
Was this page helpful?