How do I return only selected certain fields in Strapi?

后端 未结 5 1535
独厮守ぢ
独厮守ぢ 2021-01-18 06:16

Pretty straightforward (I hope). I\'d like to be able to use the API endpoint and have it only return specified fields. I.E. something like this

http://local         


        
5条回答
  •  鱼传尺愫
    2021-01-18 07:01

    I know this is old thread but I just run into exactly same problem and I could not find any solution. Nothing in the docs or anywhere else.

    After a few minutes of console logging and playing with service I was able to filter my fields using following piece of code:

    const q = Post
      .find()
      .sort(filters.sort)
      .skip(filters.start)
      .limit(filters.limit)
      .populate(populate);
    
    return filterFields(q, ['title', 'content']);
    

    where filterFields is following function:

    function filterFields(q, fields) {
      q._fields = fields;
      return q;
    }
    

    It is kinda dirty solution and I haven't figured out how to apply this to included relation entites yet but I hope it could help somebody looking for solution of this problem.

    I'm not sure why strapi does not support this since it is clearly capable of filtering the fields when they are explicitly set. it would be nice to use it like this:

    return Post
          .find()
          .fields(['title', 'content'])
          .sort(filters.sort)
          .skip(filters.start)
          .limit(filters.limit)
          .populate(populate);
    

提交回复
热议问题