#Convex Helper getOne with a index that has two columns

4 messages · Page 1 of 1 (latest)

radiant orchid
#

Ex: await ctx.db
.query("phoneSenders")
.withIndex("by_type_and_role", (q) =>
q.eq("type", args.type).eq("role", args.role)
)
.first();

digital shoalBOT
#

Hi @radiant orchid. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can use Convex's query builder with a multi-field index to efficiently retrieve a document matching two fields, as in your example. The pattern you provided is correct:

await ctx.db
  .query("phoneSenders")
  .withIndex("by_type_and_role", (q) =>
    q.eq("type", args.type).eq("role", args.role)
  )
  .first();

This will use the compound index (e.g., by_type_and_role on ["type", "role"]) to efficiently find the first document where both type and role match the provided arguments. The order of .eq() calls must match the order of fields in the index definition.

If you want a helper function similar to getOneFrom from the convex-helpers package, you would need to ensure your helper supports multi-field indexes. The built-in getOneFrom is designed for single-field lookups, but you can use the query pattern above directly for multi-field indexes.

This approach is documented and recommended for efficient querying with multiple fields in Convex, as shown in the official docs and examples:

If you need to retrieve a unique document (expecting only one match), you can use .unique() instead of .first(), but .first() is appropriate if you just want the first match and are not enforcing uniqueness.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@radiant orchid Kapa.ai is still learning and improving, please let me know how I did by reacting below.