Filter the data

HI Team,

Good Morning!

I have a collection. I need to filter based on another field .

Example

{"PostID":"1","PostDescription":"Post 1","slug":"post-1","user_groups":[{"groupname":"group1"},{"groupname":"Group2"}]}
{"PostID":"2","PostDescription":"Post2","slug":null,"user_groups":[]}
{"PostID":"3","PostDescription":"Post3","slug":"post3","user_groups":[{"groupname":"group1"},{"groupname":"Group2"}]}

I need to show only the record which is having group1.

So,my custom controller should return post1 and post3.

I have created a custom custom controller. i tried to filter with in operator . not working .

even i tried for loop is also. not working . please advice.

return entities

      .map((entity) =>

        sanitizeEntity(entity, { model: strapi.models.posts})

      )

      .filter((d) => {

        let res = false;

        for (let i = 0; i < d.user_groups.length; i++) {

          for (let j = 0; j < ctx.state.user.user_groups.length; j++) {

            if (ctx.state.user.user_groups[j].id === d.user_groups[i].id) {

              res = true;

            }

          }

        }

        return res;

      });

I am getting d.length is undefined. please help me

thanks

Hi Team

please update me regarding this.

Thanks!

You should provide the filter in the request and not through a loop in the code here. I assume this is in a controller so you should have something like strapi.services.post.find() in the controller and you can pass in some filters to that so something like strapi.services.post.find({ "user_groups": ctx.state.user["user_groups"].id })

Users can have multiple user groups. its working with

entities = await strapi.query(‘posts’).find({ ‘user_groups.id_in’: arrayOfUsergroups});

thanks for yoursupport