#Getting only some fields from query

3 messages · Page 1 of 1 (latest)

smoky kestrelBOT
#

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

#

In Convex, queries always return entire documents, but you can map over the results to select only the fields you need. Here's how you can query documents by userId and return only the name and _creationTime fields:

export const getUserData = query({
  handler: async (ctx) => {
    const documents = await ctx.db
      .query("yourTableName")
      .withIndex("by_userId", (q) => q.eq("userId", ctx.auth.userId))
      .collect();
    
    return documents.map((doc) => ({
      name: doc.name,
      _creationTime: doc._creationTime
    }));
  }
});

This approach first retrieves the full documents using the index, then maps over the results to return only the fields you need. While it might seem inefficient to retrieve all fields when you only need a few, Convex is designed to be very fast by default Stack.

If you're using pagination, you can apply the mapping to the paginated results:

export const getUserDataPaginated = query({
  args: { paginationOpts: v.any() },
  handler: async (ctx, args) => {
    const results = await ctx.db
      .query("yourTableName")
      .withIndex("by_userId", (q) => q.eq("userId", ctx.auth.userId))
      .paginate(args.paginationOpts);
    
    return {
      ...results,
      page: results.page.map((doc) => ({
        name: doc.name,
        _creationTime: doc._creationTime
      }))
    };
  }
});
#

As noted in the documentation, "Reading entire rows from storage is usually fine because the bandwidth bottleneck is between the client and the server (SQL server or Convex server), not between the server and the underlying storage" Translate SQL into Convex Queries.

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