Tips for creating an update feature in NestJS/Prisma for an ID with several attributes?

I've been working on creating a table answer with Prisma, but I'm facing challenges in defining an update function due to the ID being composed of two foreign keys from the user and question tables.

This is my current progress:

  • schema.prisma
model Answer{
  id_question Int
  id_user String
  content String @db.VarChar(250)
  updated_at DateTime @updatedAt
  user User @relation(fields: [id_user], references: [id])
  question Question @relation(fields: [id_question], references: [id])
  @@id([id_question, id_user], name:"question_user")
}
  • answers.service.ts
 async updateAnswer(params: {
    where: Prisma.AnswerWhereUniqueInput;
    data: Prisma.AnswerUpdateInput;
  }): Promise<Answer> {
    const { where, data } = params;
    return this.prisma.answer.update({
      data,
      where,
    });
  }
  • answers.controller.ts

I am uncertain about how to define the route and specify the ID parameter in this section:

@Patch('answer/:id')
  async updateAnswer(@Param('id') id: string): Promise<answerModel> {
    return this.postService.updateAnswer({
      where: { id: Number(id) },
      data: { content: true },
    });
  }

Answer №1

When working with the Answer model that has a unique id derived from two fields - id_question and id_user, it is necessary to include both values in the where clause.

Therefore, in the answers.service.ts file, the where clause should be structured as follows:

 async updateAnswer(params: {
    where: Prisma.AnswerWhereUniqueInput;
    data: Prisma.AnswerUpdateInput;
  }): Promise<Answer> {
    const { where, data } = params;
    return this.prisma.answer.answer.update({
    where: {
      question_user: {
        id_question: 1, \\ representing the id_question value
        id_user: '1', \\ representing the id_user value
      },
    },
    data: {},
  });
  }

If you need to pass multiple parameters in the controller, check out this Stack Overflow Answer for guidance.

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

In Typescript, we can use a class to encapsulate another class and then return a generic result

Trying to wrap my head around the concept of generic classes, and now I need to dynamically create another class. However, I am uncertain about how to go about it. Class A {} Class B<T> { Return T } Const c = B(A); // which is T More context on w ...

React Material-UI - implementing custom colors in Alert component leads to error: "Cannot read properties of undefined (reading 'type')"

I've been working on customizing MUI components to match our company's design, but I've hit a roadblock. While defining my custom colors, I noticed that instead of "error" we have a color called "danger." I followed the guidelines in the do ...

Tips for formatting numbers within a chart

One issue in my chart is that the values are not formatted correctly. For instance, I have a number 15900 and I would like it to be displayed as 15 900 with a space between thousands and hundreds. Below is the code snippet I would like to implement for s ...

The best approach to typing a FunctionComponent in React with typescript

I'm diving into the world of React and TypeScript for the first time. Could someone verify if this is the correct way to type a FunctionComponent? type ModalProps = { children: ReactElement<any>; show: boolean; modalClosed(): void; }; co ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

Having trouble with Prisma nextauth after changing the user model name from User to XYZUser

In my current project, we are using Nextjs, Next-auth, Prisma adapter, and Supabase for user authentication. Everything was working smoothly when the database model was named 'User'. However, after changing the model name to 'WebUser', ...

What is the best way to establish a database connection, perform a select query, and close the connection using

When working with an Oracle database using node-oracledb, the API offers promises that can be transformed into Observable<T>. My goal is to achieve the following with Observables: Establish a connection to the database Retrieve N records Close the ...

Overlap with upper picture formatting

I've been struggling to create an ion-card with two images: a main picture and a small book cover. Any ideas on how to achieve this? Note: The layout should have 2 images, one at the top and another as a small book cover. Check out this sample on St ...

Utilize Angular 2 form group to manage control activation and deactivation on forms

Just starting out in Angular 2 and I have a question that needs answering: I've created a form using Angular 2 which consists of multiple controls. These controls are dependent on each other, for instance: Check out this diagram for reference If rad ...

Errors occurred in Typescript and Next.js due to an unexpected token 'export'

I am currently working on developing an online board app using React, Next.js, and TypeScript as a project for my portfolio. This is my first time using TypeScript. However, I encountered an issue with importing roughjs into canvas.tsx. Below is the code ...

What is the method for accessing global variables and functions within JavaScript scripts imported from the index.html file and utilizing them in a component?

In my Angular 6 project, I am facing an issue with accessing a private JavaScript library that is imported in the index.html file. The functions in this library are globally scoped, but when I try to access them inside a component, Angular does not recog ...

Issue: Generated fewer hooks than anticipated. This situation could be a result of an unintentional premature return statement

view image description see image here I encountered an issue while trying to retrieve a specific item from my customer list on the first attempt. The strange behavior occurs when I search for a name not present in the table, then search for an existing en ...

Hiding a div after three clicks using HTML

What is the best way to hide a div tag containing an input tag after clicking on the input tag three times using HTML and angular? ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Using Material UI Slider along with Typescript for handling onChange event with either a single number or an

Just diving into Typescript and encountered an issue with a Material UI Slider. I'm trying to update my age state variable, but running into a Typescript error due to the typing of age being number and onChange value being number | number[]. How can I ...

Select and activate a single input from multiple options in Angular

I have multiple input fields with corresponding buttons that enable the input when clicked. I would like the behavior of the buttons to work in such a way that when one button is clicked, only that specific input field is enabled while the others are disab ...

Unable to render React component after updating its state

After successfully retrieving data from my API, React is failing to render the cards. export default function Subjects() { const userApi = useUserService(); const auth = useRecoilValue(AuthAtom); const [loading, setLoading] = React.useState<boolea ...

Is there a user-friendly interface in Typescript for basic dictionaries?

I'm not inquiring about the implementation of a dictionary in Typescript; rather, I'm curious: "Does Typescript provide predefined interfaces for common dictionary scenarios?" For instance: In my project, I require a dictionary with elements of ...

Having trouble with linting on Typescript 3.7 within the Angular 9 tslint environment

After transitioning to Angular version 9 that includes Typescript 3.7, I observed that my tslint is not identifying new features like optional chaining and null coalescing. Should I consider switching to eslint, or is there a solution to address this iss ...

The message states that the variable "Chart" has not been defined

I have been attempting to integrate ChartJS with Angular2, but I keep encountering an error message stating that 'Chart is not defined'. I made sure to install the ChartJS typings and referenced them accordingly. Additionally, I included the char ...