Search code examples
javascriptnode.jsmongodbstrapi

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?


Solution

  • 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