bmccormickB
Convex Community6mo ago
6 replies
bmccormick

Question about how to structure queries

Hi - i was wondering what kind of optimizations you do on the backend (i.e., how dumb can i be?) Say i have 3 tables: posts, tags, and postTagAssociation. A post can have 1 to many tags associated to it. Say i want to display all posts along with their tags on the page. I know this is an extreme example - but could i do this? Will this be optimized on the backend?
export const get = query({
    args: {},
    handler: async (ctx) => {
        const posts = await ctx.db.query('Posts').collect();

        return await Promise.all(
            posts.map(async (post) => {
                const tags = await ctx.db
                    .query('PostTagAssociation')
                    .withIndex('by_post', (t) => t.eq('postId', post._id)
                    .collect();

                const tagNames = await Promise.all(
                    tags.map(async (t) => {
                        if (!t.tagId) return null;
                        return await ctx.db.get(t.tagId);
                    })
                );

                return { ...post, tags: tagNames.filter(Boolean) };
            })
        );
    }
});
Was this page helpful?