简体   繁体   中英

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

I've just started using StrapiJS, and it's really great so far, but now I've come across a problem.

When creating adding some data to the database, Strapi automatically creates some fields - like created_by and updated_by fields, but I'm not getting them in the API response.

This is the data stored in 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"
    }
}

And this is the API response:

{
        "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"
    }

Is there a way to get the created of the data in the API response?

You will have to override the findOne method in your controller like below without the sanitize:

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

refer: Backend customization

set populateCreatorFields=true in model.settings.json

This seem to work for me

Add

"populateCreatorFields": true

Add Optional

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

to

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

...

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

...

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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