ChristianC
Convex Communityโ€ข2y agoโ€ข
3 replies
Christian

Efficiency of doing joins in JavaScript

So i was exploring convex, and following the react tutorial to get the gist of what convex provides. I ran into this bit of code.
export const list = query({
  args: {},
  handler: async (ctx) => {
    // Grab the most recent messages.
    const messages = await ctx.db.query("messages").order("desc").take(100);
    const messagesWithLikes = await Promise.all(
      messages.map(async (message) => {
        // Find the likes for each message
        const likes = await ctx.db
          .query("likes")
          .withIndex("byMessageId", (q) => q.eq("messageId", message._id))
          .collect();
        // Join the count of likes with the message data
        return {
          ...message,
          likes: likes.length,
        };
      })
    );
    // Reverse the list so that it's in a chronological order.
    return messagesWithLikes.reverse().map((message) => ({
      ...message,
      // Format smileys
      body: message.body.replaceAll(":)", "๐Ÿ˜Š"),
    }));
  },
});

How can this be efficient? No join, and simply looping over messages to get all required data? I get it's only querying 100 docs here but this seems to be a reverse of what I would be thinking about doing with something like postgresql or really anything besides firebase.
Was this page helpful?