Unable to populate two levels deep

Hi!

I am struggling with populating my API response correctly.

I am creating a custom controller to return a list of posts. Attached to each post should be the post’s category, as well as the likes, the post received. Attached to each like in turn, should be the ID of the user, that made the like.

Now i tried the following:

        let data = await strapi.entityService.findMany('api::post.post', {
            populate: {
                post_category: true,
                post_likes: {
                    populate: 
                    {
                        user_permissions_user: true,
                    },
                }
            },
        });

First of all that doesn’t work, I don’t receive the User Objects back with my response (it doesn’t get populated). Second of all I believe there is a select-feature i could use, so that i don’t get the entire user-object, but could maybe really just add the ID to the post_like ID in a field of it’s own.

Could someone please help me here, I’ve been trying for hours now with docu and google to fix this, but I’m really struggling :confused:

PS: I’ve made sure permissions are set correctly!

Cheers,
Max

I was able to resolve this on my own and decided to post the result here, maybe it helps someone else:

Quick Explanation:

  • This is a custom controller supposed to return a list of posts, filtered by some criteria relevant for me
  • For each post the post_category, as well as the post_like should be returned
  • For each post_like in turn, the user that made the like should be returned
  • Additionally, the response should be filtered: Only likes made by the requesting user should be returned
  • By doing this I was able to drastically reduce my backend calls, as I can now easily determine whether I should present a post as liked to the user viewing it or not

const jwt_decode = require('jwt-decode');

async filteredList(ctx) {
        // get jwt from header and check if user is premium
        const jwt = ctx.request.header.authorization;
        const userId = jwt_decode(jwt).id;

        let data = await strapi.entityService.findMany('api::post.post', {
            populate: {
                post_category: true,
                post_likes: {
                    populate: 'users_permissions_user',
                    filters: {
                        users_permissions_user: {
                            id: userId
                        }
                    },
                },
            },
    });
1 Like