Saving many-to-many relationships with entities that are already saved in TypeORM

As a beginner in Typeorm, I have been working on a web page with Angular + Typeorm for the past few weeks. Despite my efforts to resolve this issue by myself and researching previously asked questions here on Stackoverflow, I have unfortunately been unable to make any progress recently. So, here's my question: I have two entities, each having a many-to-many relationship between them.

@Entity("noticias")
@Unique(["idnoticias"])
export class Noticias extends BaseEntity{

    @PrimaryGeneratedColumn()
    idnoticias: number;

    @Column({type: "text", nullable: true})
    tituloNoticia: string;

    @Column({type: "text", nullable: false})
    contenidoNoticia: string;

    @Column({type: "text", nullable: true})
    usuario: string;

    @Column({type: "date", nullable: false})
    fechaCreacion: Date;

    @Column({type: "date", nullable: true})
    fechaPublicacion: Date;

    @ManyToMany(type => Etiquetas, etiqueta => etiqueta.noticias)
    @JoinTable()
    etiquetas: Etiquetas[];

}
@Entity("etiquetas")
@Unique(['idetiquetas'])
export class Etiquetas extends BaseEntity {
    
    @PrimaryGeneratedColumn()
    idetiquetas: number;

    @Column({type: "text", nullable: false})
    nombre: string;

    @ManyToMany(type => Noticias, noticia => noticia.etiquetas)
    @JoinTable()
    noticias: Noticias[];
}

In addition, I have a post function that receives a 'Noticias' entity and saves it into the database.

static postNoticia = async (req: Request, res: Response)=>{
        try {
            const {
                tituloNoticia,
                contenidoNoticia,
                usuario,
                fechaCreacion,
                fechaPublicacion,
                etiquetas
            } = req.body;
            
            const noticia = Noticias.create({
                tituloNoticia: tituloNoticia,
                contenidoNoticia: contenidoNoticia,
                usuario: usuario,
                fechaCreacion: fechaCreacion,
                fechaPublicacion: fechaPublicacion,
                etiquetas: etiquetas,
            });
            await noticia.save();
            return res.json(noticia);
        } catch(e) {
            console.log(e);
            res.status(500).json({message: 'Error'});
        }
        
    };

My goal is simple: when the 'postNoticia' function receives a request with an array of 'Etiquetas' objects, instead of saving all objects again in the database, I want it to check if they already exist, load them, and instantiate the many-to-many relation with the new 'Noticias' object to avoid duplicate entries. I initially tried using cascades, but it just inserts all 'Etiquetas' objects again, which is not what I want. The objective is to establish relations with existing IDs without inserting duplicates. I have read the official documentation, but the example provided does not address this issue clearly. I believe it should search for existing objects in the database, retrieve their IDs, and create the relation accordingly. However, despite my efforts, I haven't been able to make it work. If this question has already been answered elsewhere, please let me know so I can close it. Thank you in advance.

Answer №1

After much trial and error, I was able to achieve my goal by retrieving existing data if available, and creating it if not. Subsequently, I saved the Noticia object again.

static postNoticia = async (req: Request, res: Response)=>{
    try {
        const {
            titleNews,
            contentNews,
            user,
            creationDate,
            publicationDate,
            tags
        } = req.body;
        
        const news = News.create({
            titleNews: titleNews,
            contentNews: contentNews,
            user: user,
            creationDate: creationDate,
            publicationDate: publicationDate,
            tags: tags,
        });
        await news.save();
       
        let totalTags: Tags[] = [];
        for (let i = 0; i < tags.length; i++) {
            console.log(tags[i].name);
            const temp = await Tags.findOne({name: tags[i].name}); 
            if(temp == null) { //if it's a new tag that is not in the database
                let t1 = Tags.create();
                t1.name = tags[i].name;
                await t1.save();
                totalTags.push(t1);
            } else {
                totalTags.push(temp);
            }
        }
        news.tags = totalTags;
        await news.save();
        
        return res.json(news);
    } catch(e) {
        console.log(e);
        res.status(500).json({message: 'Error'});
    }
    
};

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

The error message "Unable to access property 'open' of an undefined menu" is being displayed in a TypeScript code

I am facing an issue with the action in my menu. For this project, I am using a material menu and icons. The main menu code appears as follows: <mat-menu #rootMenu="matMenu" [overlapTrigger]="false"> <ng-template matMenuContent let-element="ele ...

Behavior of Shadow DOM role when using the <a> element without an href attribute

Recently, I started working with the shadow DOM and encountered a strange issue: In my Ionic Angular application, there is a text styled like a link in this form (simplified): <a href="${ifDefined(this.href)}">link</a> When testing ...

The field list contains an unidentified column named 'Test.computerIDComputerID'

I am currently navigating through the syntax of typeORM and have been stuck troubleshooting an issue for quite some time. It appears that whenever I utilize the find() function in typeORM, a query is generated with a duplicated column from a relation. Here ...

When using Jest + Enzyme to test a stateful class component, encountering problems with Material-UI's withStyles functionality is a common issue

I have a React + TypeScript application with server-side rendering (SSR). I am using Material-UI and following the SSR instructions provided here. Most of my components are stateful, and I test them using Jest + Enzyme. Below is an example of one such com ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

`Unable to update the checked prop in MUI switch component`

The value of RankPermission in the switchPermission function toggles from false to true, but for some reason, the MUI Switch component does not update in the browser. I haven't attempted any solutions yet and am unsure why it's not updating. I&ap ...

Can we rely on the security of Ionic 4 secure storage encryption?

I'm currently developing an application that necessitates the user to be in close proximity to a specific GPS location. At present, I am obtaining their location every 30 seconds, transmitting it to my server, checking if they are near the desired loc ...

Error: The function was expecting a mapDiv with the type of Element, but instead undefined was passed - google

I have a map within a div tagged with #mapa. Whenever I try to plot a route on the map, it refreshes. I don't want the map to refresh, and here is the code I currently have: <div style="height: 500px; width: auto;" #mapa> <google-map heigh ...

What is the best way to transfer a @ContentChild attribute to a fairy tale?

Is there a way to transfer an attribute from a component with a @ContentChild decorator to a story? Below is the code for the container component: @Component({ selector: 'app-header', templateUrl: './header.component.html', style ...

Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below [ { "subjectID": 1 "Chosen" : "{subjectsChosen:Python,java,Angular}" "password": "{studentpw:123456abcd}" }, { "subjectID": 2 ...

Keep the code running in JavaScript even in the presence of TypeScript errors

While working with create-react-app and typescript, I prefer for javascript execution not to be stopped if a typescript error is detected. Instead, I would like to receive a warning in the console without interrupting the UI. Is it feasible to adjust the ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Strategies for handling multiple HTTP requests in Angular using RXJS

Within this demonstration application, we have the following structure: A list of articles (loaded upon page initialization) Each article contains a nested object called detail, which is loaded lazily Clicking on an article item will load its details. H ...

Encountering issues with Angular2 forms while working with JavaScriptServices/Universal

My Angular2 app was built using the JavaScriptServices starter from GitHub. The issue I'm encountering is a runtime error when I include a form in a component. Both FormsModule and ReactiveFormsModule are being imported. This is how my form is stru ...

Tips for deleting a specific choice with Angular

Having recently started working with Angular2 / TS / ES6, I am struggling to find a solution to my issue. I have a select element with dynamically rendered options using ngFor from an array. These options are meant for selecting attributes for a product. ...

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

Retrieving values from an array in a JSON response using Angular 4

How can I access the SubjectCode field in an array at a table using Angular 4? When trying to do so, I receive the error message: "[Error trying to diff '[object Object]'. Only arrays and iterables are allowed]". Here is the Json Response: { ...

How can you first fetch a small number of records from the service and then the remaining ones?

Is there a way to fetch the initial few records from a service followed by the rest of the records? My datatable service currently loads all entries at once, causing delays in loading time. I am looking for a solution where only a portion of the records ca ...

Issue with Angular 2 view not refreshing after receiving ipcRenderer.on event in Electron

Utilizing ipcRenderer to fetch the folder path from a browser dialog in my main.js. However, it is not updating the text string on my view for some unknown reason. I am aware that using setTimeout could potentially fix this issue (thanks Google!). Yet, e ...

An issue has occurred: the function cannot be applied to the intermediate value that is currently being processed

I am currently working on an Angular 5 CRUD application, utilizing Google Firebase services. I have been following a helpful video tutorial on YouTube (link here), but I encountered this error ngOnInit() { var x = this.employeeService.getData(); x.sna ...