Search code examples
strapi

How can I modify "fetchAll" with certain columns?


I want to limit the result of return strapi.services.myType.fetchAll (ctx.query); by selecting certain columns (SELECT column1, column2, ... not SELECT *).

How and where can I edit "ctx.query"?

Many thanks!

P.S. I also do not know exactly how to use GraphQL (for backend) for this case. Can someone give me a hint please?


Solution

  • You can do it in several ways, one of which is in your model's lifecycle function afterFetchAll(). It should work whether you're using GraphQL or not.

    afterFetchAll: async (model, response, options) => {
        model.forEach(m => {
            m.unset('column1')
            m.unset('column2')
        })
    }
    

    This way you will be able to remove any columns/fields from the fetched model array.

    And this file should be located in: api/MyType/models/MyType.js

    Ref to here for more information.