What steps can I take to prevent receiving the error message "Certain components in XXX are not associated with the entity" in Strapi?

User I am facing an issue with my application's endpoint for adding a like to a post. The endpoint is supposed to receive the user id who liked the post and insert it, along with the number of likes (not crucial at this moment), into a database. To achieve this, I first retrieve all the likes associated with a post using the following code snippet:

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

The output of this code looks something like this (although not exactly, as I need to extract this part for use in the endpoint):

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

Next, I append a new entry to this array using push, resulting in a new JSON array that resembles 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 }
]

Afterwards, I attempt to update the likes field in my database with this modified array as follows:

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

However, I encounter the error message stating "Some of the provided components in likes are not related to the entity," even though the id 2 does exist within my users. Interestingly, manually adding the same record ({id: 2, no_of_likes: 21}) through the Strapi content manager works perfectly fine. How can I resolve this issue programmatically via the endpoint?

Answer №1

If you're looking for a more efficient way to handle likes on posts, I would suggest creating a collection using the following structure:

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

To ensure that your current implementation functions correctly, it's important to exclude component ids from the JSON data. Strapi has a tendency to recreate components during edits, so keep that in mind.

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}))

After that, you can proceed with updating the entry by using the code snippet below:

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

This approach should help resolve any issues with the like functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capture the current state of a page in Next.js

As I develop my Next.js application, I've encountered an architectural challenge. I'm looking to switch between routes while maintaining the state of each page so that I can return without losing any data. While initialProps might work for simple ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: Query How can I enable real-time inspections to occur immediately? (I've already attempted invali ...

Guide: Ensuring the validity of an object retrieved from a database with Nest.js class-validator

When activating a user, I need to ensure that certain optional data in the database is not empty by using class-validator dto. So far, my controller level validations for body, query, and all other aspects have been successful. The DTO file contains vali ...

Using TypeScript to set an HTMLElement in a web page

Currently in the process of transitioning my old JavaScript code to TypeScript. One of the components I have is a Table Of Contents JSX component that helps me navigate easily to specific headings. I had a function that calculated the total offset needed ...

Error with Typescript types when using Styled Components

After successfully setting up styled-components in react-native, I encountered an issue while trying to use it in a simple example with react-native-web: import * as React from 'react'; import styled from 'styled-components'; export d ...

django: no data was submitted in request.POST

I am facing an issue with a REST API endpoint I have created. Here is the code snippet: def post(request, *args, **kwargs): print(request.POST) short_description = request.POST.get("short_description", "") long_description = re ...

Error encountered with ts-loader in the node_modules/@types directory within Webpack

After successfully compiling my project, I encountered errors when trying to run npm install and then webpack in a new directory. The errors are as follows: ERROR in /home/nobody/myproject/server/node_modules/@types/mongodb/index.d.ts (500,12): error TS10 ...

Consolidate type definition within a tsx file using VS Code

Whenever I define a type in a TypeScript file (.ts) on VS Code, I notice that there is no option to collapse the definition. Here's an example: export type Test = { someValue: string, someOtherValue: string, yetAnotherValue: string }; I ...

Having trouble locating the TypeScript compiler in Visual Studio 2017?

In an attempt to develop an application in Visual Studio using TypeScript, I meticulously followed the instructions outlined here and proceeded to install the necessary TypeScript compiler for version 2.2 of the project via NPM. npm install typescript ...

Subclasses do not have the ability to invoke methods and properties

My intention is to utilize different low-level implementations in various environments while abstracting the specific details from higher-level modules. The expectation is to have a standard way of using the class on the outer layer. The buildEnv variabl ...

Error: The page you are trying to access does not have a valid default export. The provided type is not acceptable

Hello, I am a newcomer to the world of react and NextJS. Currently, I am working on a small project using NextJS 13 where I am attempting to display products stored in a JSON file (which will later be moved to a database). The application runs correctly, ...

Unable to initiate ngModelChange event during deep cloning of value

I've been struggling to calculate the sum of row values, with no success. My suspicion is that the issue lies in how I am deep cloning the row values array when creating the row. const gblRowVal1 = new GridRowValues(1, this.color, this.headList ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

Creating an array of Form Groups involves first initializing an empty array and then

Here is a JSON object that I need to create a reactive form based on. What steps should I take for the array portion specifically? { "examName" : "java", "password" : "1234.com", "examCategory" : { "id" : 78 }, "examDetailSet" ...

Transforming a REST API get call into GraphQL

I'm currently using a REST API that accepts a code parameter, searches the database for matches, returns results if the parameter exists, and redirects users to a long_url retrieved from the database. How can I convert this functionality to GraphQL? i ...

What could be causing the issue of todo items not displaying correctly in the specified React component? (Using ASP.NET Core 2.0 with ReactJS and TypeScript)

Hello everyone, I am seeking some assistance and guidance on a React/Typescript issue I am facing with my new demo app. As a beginner in React/Typescript, I am using Visual Studio 2017 Community with asp.net core 2.0 and the react boiler project template. ...

Transform the code provided by bundleMDX into an HTML string specifically for RSS, all the while utilizing the mdx-bundler

I am currently working on developing an RSS reader and I need to convert the code returned by bundleMDX into a string. This is necessary so that I can utilize it with ReactDOMServer.renderToStaticMarkup(mdx) in my project. You can find a similar implement ...

Encountering an error in Angular where the property does not exist in type

Struggling to create a collapsible menu within my header component in an Angular project, I've hit a snag with proper JSON formatting. The error message that keeps popping up reads: Error: src/app/components/header/header.component.html:48:49 - error ...

What is the proper way to define a generic function that accepts a Union type as an argument?

I am dealing with various types and their unions. Here is the code snippet: type A = { name: string } type B = { work: boolean } type AB = A[] | B[] const func = (): AB => { return [{ name: 'ww' }] } const data = ...