繁体   English   中英

如何在 StrapiJS 中获取由字段创建和更新的字段?

[英]How can I get the created by and updated by fields in StrapiJS?

我刚刚开始使用 StrapiJS,到目前为止它真的很棒,但现在我遇到了一个问题。

在创建向数据库添加一些数据时,Strapi 会自动创建一些字段 - 例如created_byupdated_by字段,但我没有在 API 响应中得到它们。

这是存储在 MongoDB 中的数据:

{
    "_id": {
        "$oid": "606fd90b0057c05954d29f50"
    },
    "likes": 0,
    "dislikes": 0,
    "Title": "Why is this not working?",
    "Subtitle": "I really don't know",
    "slug": "why-is-this-not-working",
    "content": "**I DO NOT KNOW**",
    "published_at": {
        "$date": "2021-04-09T04:33:17.304Z"
    },
    "createdAt": {
        "$date": "2021-04-09T04:33:15.232Z"
    },
    "updatedAt": {
        "$date": "2021-04-09T04:33:17.316Z"
    },
    "__v": 0,
    "created_by": {
        "$oid": "606f1a45af15265f780983ce"
    },
    "updated_by": {
        "$oid": "606f1a45af15265f780983ce"
    }
}

这是 API 响应:

{
        "likes": 0,
        "dislikes": 0,
        "_id": "606fd90b0057c05954d29f50",
        "Title": "Why is this not working?",
        "Subtitle": "I really don't know",
        "slug": "why-is-this-not-working",
        "content": "**I DO NOT KNOW**",
        "published_at": "2021-04-09T04:33:17.304Z",
        "createdAt": "2021-04-09T04:33:15.232Z",
        "updatedAt": "2021-04-09T04:33:17.316Z",
        "__v": 0,
        "id": "606fd90b0057c05954d29f50"
    }

有没有办法在 API 响应中创建数据?

您将不得不覆盖 controller 中的 findOne 方法,如下所示,无需进行清理:

async findOne(ctx) {
     const { id } = ctx.params;    
     const entity = await strapi.services.blogPost.findOne({ id });
     // return sanitizeEntity(entity, { model: strapi.models.blogPost});
     return entity;
}

参考: 后端定制

在 model.settings.json 中设置populateCreatorFields=true

这似乎对我有用

添加

"populateCreatorFields": true

添加可选

"publicAttributes": ["created_at", "updated_by"]

api/blog-post/models/blog-post.settings.json

...

"options": {
    "increments": true,
    "timestamps": true,
    "draftAndPublish": true,
    "populateCreatorFields": true
  }

...

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM