ralf
ralf2w ago

How to "include" relation properly?

is this the best way in convex to "include" an author name?
No description
4 Replies
erquhart
erquhart2w ago
Yep, that's the way, but it can be less formal
export const getPitchQuestions = query({
args: { pitchId: v.id("pitches") },
handler: async (ctx, { pitchId }) => {
const questions = await asyncMap(
await ctx.db
.query("questions")
.withIndex("by_pitch", (q) => q.eq("pitchId", pitchId))
.collect(),
async (q) => {
const author = await ctx.db.get(q.authorId);
return { ...q, authorName: author?.name ?? "Unknown Player" };
}
);
return questions.sort((a, b) => {
const av = a.votes ?? 0;
const bv = b.votes ?? 0;
if (av != bv) return bv - av; // votes desc
return (a.createdAt ?? 0) - (b.createdAt ?? 0); // createdAt asc
});
},
});
export const getPitchQuestions = query({
args: { pitchId: v.id("pitches") },
handler: async (ctx, { pitchId }) => {
const questions = await asyncMap(
await ctx.db
.query("questions")
.withIndex("by_pitch", (q) => q.eq("pitchId", pitchId))
.collect(),
async (q) => {
const author = await ctx.db.get(q.authorId);
return { ...q, authorName: author?.name ?? "Unknown Player" };
}
);
return questions.sort((a, b) => {
const av = a.votes ?? 0;
const bv = b.votes ?? 0;
if (av != bv) return bv - av; // votes desc
return (a.createdAt ?? 0) - (b.createdAt ?? 0); // createdAt asc
});
},
});
ralf
ralfOP2w ago
but this needs so many db calls, can't this be optimized?
erquhart
erquhart2w ago
It seems to be a lot of calls compared to a sql command or orm because the api is low level, eg., it doesn't perform joins for you automatically. But sql and orm's are still doing this many db calls for joins under the hood, you're just not exposed to the semantics. Here you're fetching n records and then +1 for each author. You could start trying to optimize by, eg., stashing the authors in an array and checking there before a db call, but Convex is already doing that kind of caching for you under the hood. Most attempts to optimize early end up being wasted with Convex because they've thought through so much of this in the api design. I have a ton of premature optimization in my own code that will probably just always be there now lol. My recommendation is resist the urge to optimize, and just write code that works. Then see how it performs in practice. Not having to think about so much is a massive benefit of using Convex.
ralf
ralfOP5d ago
I see! thank you so much for this!

Did you find this page helpful?