kingyml
kingyml4mo ago

Error when using withIndex (Index not found)

I can't seem to get indexes to work at all. I keep getting an Index not found error. I have attached the error message, my schema and query. I am able to get the query to work using filter but I want to take advantage of withIndex for perfomance. I even tried just a simple userId index and that didn't work either. Same error. Any idea what I could be doing wrong?
No description
No description
No description
4 Replies
kingyml
kingymlOP4mo ago
Here is the query that's not working
export const getTestItems = query({
args: {
category: v.string(),
},
handler: async (ctx, args) => {
const user = await authenticateUser(ctx);
const { category } = args;

console.log("Querying testItems for user:", user._id, "and category:", category);

const items = await ctx.db
.query("testItems")
.withIndex("by_userId_and_category", (q) =>
q.eq("userId", user._id).eq("category", category)
)
.collect();

console.log("Query result:", items);

return items;
},
});
export const getTestItems = query({
args: {
category: v.string(),
},
handler: async (ctx, args) => {
const user = await authenticateUser(ctx);
const { category } = args;

console.log("Querying testItems for user:", user._id, "and category:", category);

const items = await ctx.db
.query("testItems")
.withIndex("by_userId_and_category", (q) =>
q.eq("userId", user._id).eq("category", category)
)
.collect();

console.log("Query result:", items);

return items;
},
});
this query below works fine
export const getAllTestItems = query({
handler: async (ctx) => {
const user = await authenticateUser(ctx);

console.log("Querying all testItems for user:", user._id);

const items = await ctx.db
.query("testItems")
.filter((q) => q.eq(q.field("userId"), user._id))
.collect();

console.log("Query result:", items);

return items;
},
});
export const getAllTestItems = query({
handler: async (ctx) => {
const user = await authenticateUser(ctx);

console.log("Querying all testItems for user:", user._id);

const items = await ctx.db
.query("testItems")
.filter((q) => q.eq(q.field("userId"), user._id))
.collect();

console.log("Query result:", items);

return items;
},
});
kingyml
kingymlOP4mo ago
In the convex logs I can confirm the userId and category name is valid.
No description
sshader
sshader4mo ago
Things I'd check: * Your convex/schema.ts defines the index (name matches, fields match) * Your npx convex dev command has run successfully * The index shows up in the Dashboard under Data > testItems > three dot menu > Schema and Indexes
kingyml
kingymlOP4mo ago
Great this worked! My issue was in the schema.ts file. I didn't have it set up correctly. Thank you so much

Did you find this page helpful?