# 如何填写创建者字段

> Source: https://strapi.nodejs.cn/cms/api/rest/guides/populate-creator-fields

在内容类型模式中启用 `populateCreatorFields` 选项，并创建路由中间件以在 REST API 响应中包含 `createdBy` 和 `updatedBy` 字段。

🌐 Enable the `populateCreatorFields` option in a content-type schema and create a route middleware to include `createdBy` and `updatedBy` fields in REST API responses.

创建者字段 `createdBy` 和 `updatedBy` 默认从 [REST API](/cms/api/rest) 响应中移除。通过在内容类型级别激活 `populateCreatorFields` 参数，这两个字段可以在 REST API 中返回。

🌐 The creator fields `createdBy` and `updatedBy` are removed from the [REST API](/cms/api/rest) response by default. These 2 fields can be returned in the REST API by activating the `populateCreatorFields` parameter at the content-type level.

:::note

`populateCreatorFields` 属性在 GraphQL API 中不可用。

🌐 The `populateCreatorFields` property is not available to the GraphQL API.

只有以下字段会被填充：`id`、`firstname`、`lastname`、`username`、`preferedLanguage`、`createdAt` 和 `updatedAt`。

🌐 Only the following fields will be populated: `id`, `firstname`, `lastname`, `username`, `preferedLanguage`, `createdAt`, and `updatedAt`.

:::

将 `createdBy` 和 `updatedBy` 添加到 API 响应中：

🌐 To add `createdBy` and `updatedBy` to the API response:

1. 打开内容类型为 `schema.json` 的文件。
2. 将 `"populateCreatorFields": true` 添加到 `options` 对象中：

  ```json
  "options": {
      "draftAndPublish": true,
      "populateCreatorFields": true
    },
  ```

3. 保存 `schema.json`。
4. 可以使用 [generate CLI](/cms/cli.md) 创建一个新的路由中间件，或者通过在 `./src/api/[content-type-name]/middlewares/[your-middleware-name].js` 中手动创建一个新文件来实现
5. 添加以下代码，你可以修改此示例以满足你的需要：

  ```js title="./src/api/test/middlewares/defaultTestPopulate.js"
  "use strict";

  module.exports = (config, { strapi }) => {
    return async (ctx, next) => {
      if (!ctx.query.populate) {
        ctx.query.populate = ["createdBy", "updatedBy"];
      }

      await next();
    };
  };
  ```

6. 修改你的默认路由工厂，以在你希望此群体应用的特定路由上启用此中间件，并将内容类型/中间件名称替换为你的内容类型/中间件名称：

  ```js title="./src/api/test/routes/test.js"
  "use strict";

  const { createCoreRouter } = require("@strapi/strapi").factories;

  module.exports = createCoreRouter("api::test.test", {
    config: {
      find: {
        middlewares: ["api::test.default-test-populate"],
      },
      findOne: {
        middlewares: ["api::test.default-test-populate"],
      },
    },
  });
  ```

没有 `populate` 参数的 REST API 请求默认会包含 `createdBy` 或 `updatedBy` 字段。

🌐 REST API requests with no `populate` parameter will include the `createdBy` or `updatedBy` fields by default.
