Creating a one-to-many relationship in NestJS using TypeORM and saving data efficiently

I'm currently working on a NestJS project where I need to save an array of objects in a one-to-many relationship.

The frontend provides me with the following structure:

[
{
"actor":"actorname",
"role":"actorrole"
},
{
"actor":"actorname2",
"role":"actorrole2"
}
]

To achieve this, I have created entities for movies and actors as follows:

actor.entity.ts

//imports
@Entity()
export class Actor {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(() => Movie, (movie) => movie.actors)
    movieId: number;

    @Column()
    role: string;

    @Column()
    actor: string;
}

movie.entity.ts

//imports
@Entity()
export class Movie {
    @PrimaryGeneratedColumn()
    id: number;

    //more stuff

    @OneToMany(() => Actor, (actor) => actor.movieId)
    actors: Actor[];
}

The challenge lies in the fact that the frontend sends the JSON data as a single string. Therefore, I need to parse it before accepting it in my DTO like so:

//imports
export class CreateMovieDto {
    actorsArray: string;
}

My current hurdle is saving the parsed JSON data:

//imports
@EntityRepository(Movie)
export class MoviesRepository extends Repository<Movie> {
    async createMovie(
        createMovieDto: CreateMovieDto,
        fileName: string,
        filePath: string,
    ) {
        const movie = this.create(createMovieDto);

        let actorsArray = JSON.parse(createMovieDto.actorsArray);
        //how do i save it now together with the movie?
        
        try {
            //await this.save(movie); disabled for now
            return movie;
         } catch (error) {
            if ((error.code = 'ER_DUP_ENTRY')) {
                console.log(error);
                throw new ConflictException('Movie already exists');
            } else {
                console.log(error);
                throw new InternalServerErrorException();
            }
        }
    }

Answer №1

Try implementing a solution similar to this

//Is there a way to save it alongside the movie?

const actorsEntities = await Promise.all(actorsArray.map(async (actor) => {
    const actorEntity = new Actor(actor);

    // Saving the actor entity in the database
    await this.actorsRepository.save(actorEntity);

    return actorEntity;
}));

movie.actors = actorsEntities;
this.save(movie);

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

Aggregate data by month, even if some months have no data

I need to retrieve all order values for each month. I have been using GROUP BY month to achieve this, but it only works for months that have orders in them. I also want to include months with no orders so that I can view all months. This is the query I am ...

Find the final day of the upcoming month

Could I retrieve the final date of each month for the next 12 months? For instance, in the format (YYYY-MM-DD) Complete year: Today's date: 2014-05-09 1st month: 2014-06-09 2nd month: 2014-07-09 3rd month: 2014-08-09 4th month: ...

Protect sensitive passwords stored in a database

Due to specific internal requirements, it is necessary for me to store passwords for 3rd party accounts in a database. Therefore, using a hash function is not ideal as it would make retrieving the password difficult. Is there a method to encrypt the plain ...

Where does tsc look to find the ts files for compilation?

Currently, I am delving into learning AngularJS v2 by thoroughly exploring the official documentation. https://angular.io/docs/ts/latest/tutorial/toh-pt1.html https://github.com/angular/quickstart While experimenting with the tutorial mentioned in the l ...

Moving the marker does not update the address

When the dragend event is triggered, the Getaddress function will be called in the following code: Getaddress(LastLat, LastLng , marker,source){ this.http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+LastLat+ &apos ...

What is the best way to retrieve DATETIME from MySQL and save it to time_t using MySQL Connector/C++?

I am utilizing the MySQL Connector/C++ library to retrieve data from a MySQL database in my C++11 project. Specifically, I need to fetch a DATETIME field named jointime from the database and store it as a time_t variable as shown below: #include <cstdl ...

Please ensure that there is at least 6 months of activity before including

Is there a way to filter out companies based on their b2b_id that have had at least 1 invoice per month for the past 6 months? SELECT b2b_id, uid, issue_date), due_date, COUNT(*) AS cnt FROM t_invoice GROUP BY b2b_id, last_day(issue_date) HAVI ...

Having trouble with Typescript module path resolution for .js files?

I have embarked on a project in React and I am eager to begin transitioning the js files to typescript. The setup for aliases seems to function smoothly when importing .tsx within another .tsx file, however, it encounters issues when attempting to import . ...

Having difficulty employing jest.mock with a TypeScript class

Following the guidelines outlined in the ES6 Class Mocks page of the Jest documentation, I attempted to test a method on a TypeScript class called Consumer. The Consumer class instantiates a Provider object and invokes methods on it, prompting me to mock t ...

What methods does Angular use to determine the parameter types of a constructor?

I've been experimenting with replicating Angular's approach to interpreting the constructor in an injectable service. function Injectable() { return function<T extends { new (...args: any[]): {} }>(con: T) { return class extends con ...

Obtain the link to a Component

I am attempting to retrieve the current URL in Angular 8 using this._my.dialog = location.pathname.replace('/', '');, but it is not consistently returning the desired result, even when placed within ngOnInit(). This issue seems to occu ...

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

Angular TS class with an ever-evolving and adaptable style

Currently, I am working with angular 9. Does anyone know a way to dynamically change the CSS of a class in a component? .stick-menu{ transform: translate(10px,20px); } I am looking to dynamically adjust the position of x and y values. For example: .stic ...

Ways to retrieve the response object from an express application

I am currently working on developing a nodejs application with mysql and my objective is to have my controllers and messages separated into different files. Below are examples of what I am aiming for: First, here is a snippet from my auth controller file: ...

I'm searching for the types for SvelteKit load function, especially for fetch. Can someone

When working with SvelteKit, I am utilizing the load function to make an API call. My aim is to utilize the fetch that is provided in the load function - however, my project is written in TypeScript. I'm curious where I can find the type definitions ...

What is the reason that the combination type of two interfaces that expand a generic interface cannot be used for that generic interface?

Within my codebase, I've established a straightforward generic interface W. Extending this interface are two more interfaces - T and N, each adding a property type that can be utilized in a tagged union scenario: interface W<V> { value: V } ...

Guide to updating the key label within an array

I have an array below that needs to be updated with key values changed from Apple fruit to Pizza shop, Orange fruit to Kfc shop, Banana fruit to Mcdonald shop, Mango fruit to fries shop if any of the value pairs exceed 15 characters. If the character count ...

I am encountering an issue where the nested loop in Angular TypeScript is failing to return

I am facing an issue with my nested loop inside a function. The problem is that it is only returning the default value of false, instead of the value calculated within the loop. Can someone please point out what I might be doing incorrectly? Provided belo ...

What methods can I implement to enhance the capabilities of my API when my response types are defined as interfaces?

My React application requires an extension method to be added on the Product type in order to make refactoring easier. This extension method should include boolean checks such as product.hasAbc() that references the attributes property. Currently, the API ...

Encountering "Error: Class constructor vA cannot be invoked without 'new'" when using Angular 10 Kendo Grid

I am currently working on integrating a Kendo Grid into my Angular application. However, I have run into an error when enabling the Kendo Grid component: vendor.4add67dadae0cd9152b9.js:16 ERROR Error: Uncaught (in promise): TypeError: Class constructor vA ...