How do I avoid "Some of the provided components in XXX are not related to the entity" in Strapi?

129 views Asked by At

User I have an endpoint to add a like to a post in an application. The endpoint gets the id of the user who clicked on the like button and inserts that id, along with the number of likes(not important right now) in a database. To do this i first get all the likes a post has with this code:

const likes = await strapi.db.query("api::post.post").findOne({
                where: {id: postId},
                populate: [
                    "likes"
                ]
            });

This returns something like this(not exactly, but I extract this part to use in the endpoint):

[
  { id: 8, no_of_likes: 21 },
  { id: 10, no_of_likes: 13 },
  { id: 11, no_of_likes: 16 }
]

Now add a new entry to this Array with push, which gives me a new json array that looks like this:

[
  { id: 8, no_of_likes: 21 },
  { id: 10, no_of_likes: 13 },
  { id: 11, no_of_likes: 16 },
  { id: 2, no_of_likes: 22 }
]

And now I update the likes field of my database with this new array like this:

//Add user to the liked_by section.
            const entry = await strapi.entityService.update("api::post.post", postId, {
                data: {
                    likes: likesJsonObject
                }
            });

But this returns the error "Some of the provided components in likes are not related to the entity" even though the id 2 absolutely exists in my users. If I manually add that very same registry({id: 2, no_of_likes: 21}) through the strapi content manager it works and it inserts the very same thing I want to insert. How can I manage to do it programatically through the endpoint?

1

There are 1 answers

0
antokhio On

This is not the best solution to make likes for posts, generally i would recommend creating a collection with something like:

// api::post-like.post.like
{
  user: Relation => to user
  post: Relation => to post
} 

So to make your current implementation work, you have to exclude component ids from json. The way strapi works it recreates components on edit:

const components = [
  { id: 8, no_of_likes: 21 },
  { id: 10, no_of_likes: 13 },
  { id: 11, no_of_likes: 16 },
  { id: 2, no_of_likes: 22 }
].map(({id, ...component}) => ({...component}))

then

const entry = await strapi.entityService.update("api::post.post", postId, {
  data: {
    likes: components,
  }
});

should work