Can't get createdBy from api

Seems like there is an issue related with “populateCreatorFields” in the documentation. I’ll paste my answer here. Hope it helps.

Here is some workaround. It doesn’t need to set “populateCreatorFields” options. You can use strapi db query and ask to populate createdBy field.

If you use Graphql API, you need to extend the query you want

// path: ./src/index.js

module.exports = {
  register({ strapi }) {
    const extensionService = strapi.plugin('graphql').service('extension');

    const extension = ({ nexus }) => ({
      types: [
        // creating new object type called Creator
        nexus.objectType({
          type: 'Creator',
          name: 'Creator',
          definition(t) {
            t.int('id');
            t.string('firstname');
            t.string('lastname');
          },
        }),
        nexus.extendType({
          type: 'Article',
          definition(t) {
            // we want to know who is the creator
            t.field('createdBy', {
              type: 'Creator',
              async resolve(root, args, ctx) {
                // when we use query, we can populate createdBy
                const query = strapi.db.query('api::article.article');
                const article = await query.findOne({
                  where: {
                    id: root.id,
                  },
                  populate: ['createdBy'],
                });
                
                return {
                  id: page.createdBy.id,
                  firstname: page.createdBy.firstname,
                  lastname: page.createdBy.lastname,
                };
              },
            })
          }
        }),
      ],
    });

    extensionService.use(extension);
  }
}    

When I query articles, I can ask for the createdBy

query {
  articles {
    data {
      attributes {
        createdBy {
          id
          firstname
          lastname
        }
      }
    }
  }
}

If you use REST API, you can extend the controller

'use strict';

/**
 *  article controller
 */

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::article.article', ({ strapi }) => ({
  async find(ctx) {
    // Calling the default core action
    const { data, meta } = await super.find(ctx);

    const query = strapi.db.query('api::article.article');

    await Promise.all(
      data.map(async (item, index) => {
        const article = await query.findOne({
          where: {
            id: item.id,
          },
          populate: ['createdBy'],
        });
        
        data[index].attributes.createdBy = {
          id: page.createdBy.id,
          firstname: page.createdBy.firstname,
          lastname: page.createdBy.lastname,
        };
      })
    );

    return { data, meta };
  },
}));
2 Likes