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

Troubleshooting: Resolving the Error "Cannot find Property htmlFor on Custom React Component"

I am currently working with a custom component that looks like this: import React from "react"; import classnames from 'classnames'; import { ButtonVariantColor } from '../types/button'; export type IconButtonProps = { e ...

Using Angular 2 to Bind a Single Click Event to Multiple Elements

Within the component's export class, I have defined iconCheck: string;. In the constructor, I set this.iconCheck = "add_circle";. Additionally, in the export class, I have the following method: iconChange() { if(this.iconCheck == "add_circle") { ...

Update the names of the output fields within the returned object from the API

Recently I delved into nodejs and typescript to create an API using express. I attempted to return a custom object in my API structured as follows: export class Auction { private _currentPrice:number = 0; private _auctionName:string; public ...

Strategies for updating JSON file content as data evolves

I am facing an issue with loading a json file that populates charts. The file is generated from external data sources and stored in the asset directory. Is there a method to automatically load the updated json file? I have attempted to include the code fo ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

The listener for @ok is not being activated when using jest-test-utils with b-modal in vue-bootstrap

I have implemented the vue-bootstrap b-modal feature with the @ok="save" hook Here is a snippet of mycomponent.vue: <template> <div> <b-button @click="add">open modal</b-button> <b-modal static lazy id="modal-detail" ...

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

Is it possible to create an observable with RXJS that emits only when the number of items currently emitted by the source observables matches?

I am dealing with two observables, obs1 and obs2, that continuously emit items without completing. I anticipate that both of them will emit the same number of items over time, but I cannot predict which one will emit first. I am in need of an observable th ...

Creating TypeScript atom packages

Has anyone successfully implemented this before? I couldn't locate any assistance for it. If someone could provide references to documentation or existing code, that would be great. I know that Atom runs on Node and that there is a TypeScript compil ...

Issues with Router navigation in an Ionic-Angular application

I am currently working on a straightforward application using Angular 9 and Ionic 5. The main page consists of a list of items. Here is my HTML code: <ion-header> <ion-toolbar> <ion-title>recipes</ion-title> </ion-toolba ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

Issues encountered when trying to deploy Strapi on a Digital Ocean Droplet due to a breach of the specified Content Security Policy directive: "connect-src 'self' https:'

I recently started using Digital Ocean and am in the process of deploying strapi for production. After successfully setting up a new Digital Ocean droplet running Ubuntu 20, I installed Node.js on it. I also added Nginx, although I'm unsure if it&apo ...

The production build for Angular 9 Keyvalues pipe fails to compile

After successfully running my app on the development server with ng serve, I encountered a failure when trying to build it for production. The error message that popped up was: ERROR in src/app/leaderboard/leaderboard.component.html(9,17): Argument of typ ...

Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array. Here is the array: [{ name: "Computer", name: "Car", name: "House&q ...

Leveraging Angular 4-5's HttpClient for precise typing in HTTP requests

Utilizing a helper service to simplify httpClient calls, I am eager to enforce strong typing on the Observable being returned. In my service where I utilize the api Service and attempt to obtain a strongly typed observable that emits: export class ApiU ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

How to use TypeScript to set a value in ng2-ckeditor

I have implemented two ckeditor instances using *ngFor: <div class="form-group" *ngFor="let lang of languages"> <span>Legal text in {{lang.translate}} {{lang.abbr}}</span> <ckeditor id="{{lang.abbr}}" formControlName="{{lang.abbr} ...

Extending a generic typed class in Typescript allows for the creation of

I am interested in extending the following class: import 'reflect-metadata'; import { IRepository, IFireOrmQueryLine, IOrderByParams, IEntity } from './types'; import { AbstractFirestoreRepository } from './AbstractFirestoreReposit ...

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

I am experiencing an issue where the Javascript keydown event does not recognize the character "@" in the EDGE browser

Currently, I am developing a mentioning directive that displays a list of users when the user types in an input field (a div with contentEditable=true). The user can then insert the name of the desired user in a specific format. The list is supposed to be ...