Typeorm express: Enhancing data updates in a many-to-many relationship

Attempting to use both .save and .update is causing errors. When using .save, it returns an error stating: the value of a duplicate key breaks the unique constraint. On the other hand, when using .update, it returns an error saying: the "userId" column of the "user" relation does not exist.

It should be noted that there are 2 tables involved - 'role' and 'user', with an association called user_role.

 //Many-to-many relation with user
  @ManyToMany((type) => User, (user) => user.roles)
  users: User[];



//Many-to-many relation with role
  @ManyToMany((type) => Role, {
    cascade: true,
  })
  @JoinTable({
    name: "users_roles",
    joinColumn: { name: "userId", referencedColumnName: "id" },
    inverseJoinColumn: { name: "roleId" }
  })
  roles: Role[];

The source code snippet provided includes:

let entity = await this.userRepository.create(data.payload);

let entity2 = { ...entity, roles: data.payload.selectedRoles}

const user = await this.userRepository.save(entity2);
/*const user = await this.userRepository.update(id, entity2);*/
 
//todo we need to serialize the user
// return only what we need like username , email, ...etc not password!!!!
return { success: true, user: SanitizeUser(user) };

Answer №1

When updating data, it is important to first retrieve the existing data using findOne(id) and then apply the changes before saving it back. Here is an example:

const userToUpdate = await this.userRepository.findOne(id)
      let updatedData = {
        ...userToUpdate,
        username: newData.username,
        firstname: newData.firstname,
        lastname: newData.lastname,
        email: newData.email,
        company: newData.selectedCompany,
        roles: newData.selectedRoles
      }

      const updatedUser = await this.userRepository.save(updatedData);

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

Modify the characteristic of a moving component provided it meets the criteria

One of my functions, 'refreshDisplay', is designed to generate dynamic elements. However, there is a specific condition that needs to be met. In the 'src' attribute of the image, I need to check if the obj.picture.thumbnail starts with ...

Is the concept of LinkedList index applicable in the field of Data Structures and Algorithms (DSA)?

Is there an index feature in LinkedList that allows for accessing elements like in arrays? If so, can you explain how the indexing works within the LinkedList concept? Thank you I am new to LinkedList and would like to grasp the fundamental concept behin ...

How can states be passed down as props in React?

This might be a beginner question, but I've been struggling with it all day. Any help would be appreciated. Apologies for the length, I just wanted to explain everything I'm having trouble with I am attempting to create custom buttons by build ...

The closest comparison to the For In method in JavaScript in the Apex programming

I am looking for a way in Apex to iterate through all the fields of a list of account objects without having to resort to using JavaScript. Currently, I can achieve this with the following code snippet in JavaScript, but I prefer to keep things within the ...

The ID update functionality in Node.js is malfunctioning

Hello everyone, I am currently venturing into the world of NodeJS with a goal to create a backend API for a car rental agency. After writing some code to update, view, and delete records by id stored in MongoDB, I encountered a strange issue where it only ...

The angularjs ui-sortable feature is experiencing an issue where methods cannot be called on sortable before initialization. The specific method 'refresh' was attempted to be called prematurely

I'm attempting to sort a list, where I retrieve the elements from a database but... Error: unable to call methods on sortable before initialization; tried calling method 'refresh' This is my HTML: <div class="box-body" > <d ...

Equally distributing the space while adjusting the size of the browser window

When adjusting the size of the browser window, I noticed that the space after the element is reduced. I would like to decrease the space equally on both the left and right sides, similar to how it is done on Facebook. Below is the code I have: CSS: body ...

Issue with retrieving query results using node_redis client

I've been struggling with a particular issue that I just can't seem to solve. The problem revolves around not being able to retrieve output values from a Redis query. My setup involves using the node_redis client as the Redis driver for my Node.J ...

Interactive sign-in/sign-out navigation bar

I need the login button to show as log out when the user is logged in. In the index.js file: app.get('/', (request, response) => { const isAuthenticated = request.session.authenticated || false; // { user: { authenticated: isAuthenti ...

When working with Typescript, an error may occur related to index types even though the constant object and its

I am struggling with understanding TypeScript, specifically when it comes to a problem I encountered. Hopefully, someone can shed some light on this for me. My issue revolves around a functional component that is responsible for displaying the correct com ...

JavaScript encounters an unexpected identifier: Syntax Error

I encountered a syntax error while executing the code below: var userAnswer = prompt("Do you want to race Bieber on stage?") if userAnswer = ("yes") { console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!") } else { ...

Each time the server restarts, Express.js will run a function asynchronously

Looking for guidance on implementing a function in my Express.js app that can fetch data from the database and then cache it into Redis. The goal is to have this function executed only upon restarting the Web server. Any suggestions on how I can achieve t ...

Is there a way to display the items I've added to my cart when I click on it?

I have a collection of product IDs stored in local storage. I am using these IDs to populate the list of products added to the basket. Strangely, when I navigate to the basket page, the products do not appear unless I make a small code modification or re-s ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...

The "Go" button on iPhone triggers an error before the page is sent back

I am facing an issue with a web page that has a form containing multiple submit buttons with different functionalities like clearing the form, performing a calculation, or adding another entry line. The problem arises only on iPhone devices (tested on bot ...

Issue with Caching during Javascript Minification

I Have ASP.Net MVC 3 App. Utilizing YUICompressor.Net for compressing Javascript and CSS files post build with MSBuild. The minimized javascript file is named JSMin.js and the CSS file is CssMin.css. In my master page, I reference these files as shown bel ...

Is it Possible to Remove an Item from an Array in Vue without Explicitly Knowing the Array's

I'm currently working on a feature that involves removing an item from an array when it is clicked. The code I have so far looks like this: <span @click="deleteItem(index)" v-for="(item, index) in customTaxonomies.featured" v-html="item"></s ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

Accessing a peaceful API and displaying the outcome on a webpage using Node.js

I am currently working on a project that involves fetching data from a RESTful API and displaying the results on an HTML webpage using Node.js. While my code is running smoothly, I would like to ensure that the RESTful request is made every time the webp ...

Ways to showcase the object on the console

How can I display the object function in the console? When I try, nothing is displayed. Can you please help me figure out what went wrong? I know I must have made a mistake somewhere, as this is my first question on Stack Overflow. import React, ...