rochel3
rochel310mo ago

Getting specific column results

Hi guys, how do i return a list of objects containing specified columns instead of the whole record itself? Thanks guys!
4 Replies
Michal Srb
Michal Srb10mo ago
Hey @rochel3 , you can map over the results in your function:
import { query } from "./_generated/server";

export const listTasks = query({
handler: async (ctx) => {
const tasks = await ctx.db.query("tasks").collect();
return tasks.map(({name, completed} => ({name, completed}));
},
});
import { query } from "./_generated/server";

export const listTasks = query({
handler: async (ctx) => {
const tasks = await ctx.db.query("tasks").collect();
return tasks.map(({name, completed} => ({name, completed}));
},
});
In this example only the name and completed columns are returned.
rochel3
rochel3OP10mo ago
Hey @Michal Srb thanks for the quick reply
export const getSchoolsByDate = query({
args: { show_date: v.string() },
handler: async (ctx, args) => {
const _schools = await ctx.db
.query("show_dates")
.filter((q) => q.eq(q.field("show_date"), args.show_date))
.collect();
const schools: string[] = [];
_schools.map((o) => {
schools.push(o.school_name);
});
return schools;
},
});
export const getSchoolsByDate = query({
args: { show_date: v.string() },
handler: async (ctx, args) => {
const _schools = await ctx.db
.query("show_dates")
.filter((q) => q.eq(q.field("show_date"), args.show_date))
.collect();
const schools: string[] = [];
_schools.map((o) => {
schools.push(o.school_name);
});
return schools;
},
});
This was my work around, im not sure if it is efficient
Michal Srb
Michal Srb10mo ago
It is efficient (and similar to the code I gave - if you're gonna .push() you can use forEach() instead of map())
rochel3
rochel3OP10mo ago
thanks man!

Did you find this page helpful?