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

Guide on transitioning from @ngrx/store syntax version 2.2.1 to the latest version 6.1.2

Need help upgrading the syntax usage of @ngrx/store from version 2.2.1 to version 6.1.2 Upon recently upgrading my Angular project from Angular ^2.0.0 to Angular ^6.0.0 along with related npm plugins, I encountered issues with the usage of @ngrx/store and ...

Invoke a method within a function triggered by the .call() method

Currently, I am developing an n8n node that essentially functions every time a specific event occurs. To facilitate this process, I have created an abstract class which is invoked by the n8n environment. However, there seems to be a limitation in calling ...

Tips on properly declaring props in Typescript when a parent component is passing props down to its children componentsуж

When a parent component clones its children to pass props to them, how can we specify the type of props for the children? I'm encountering an issue because injectedProps is expected in the Child component const Parent: React.SFC<ParentProps> = ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...

Using AngularFire2 to manage your data services?

After diving into the resources provided by Angular.io and the Git Docs for AngularFire2, I decided to experiment with a more efficient approach. It seems that creating a service is recommended when working with the same data across different components in ...

Encountering difficulties in starting a new Angular project using a Mac operating system

Attempting to set up a fresh Angular project named 'test' on a Mac. The command used in Terminal is as follows: xxxx$ ng new test Upon execution, the following error is displayed: -bash: /Users/xxxx/.npm-packages/lib/node_modules/@angular/cli ...

Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's wha ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

Efficiently sending data to Service Bus from an HTTP-triggered function

How can I link the output to service bus? I've configured an out binding in my Azure function: { "queueName": "testqueue", "connection": "MyServiceBusConnection", "name": "myQueueItem", "type": "serviceBus", "direction": "out" } I started ...

Are multiple click events needed for identical buttons?

In my component, there is an HTML structure like this: <div id="catalogo" class="container"> <div class="row"> <div *ngFor="let artista of artistas" class="col-sm" style="mar ...

Utilizing Min and Max Validation in Angular 2 Template-Driven Forms

I attempted to incorporate min validation in a template form, but unfortunately it did not function as expected. Could someone provide guidance on how to properly use it in a template form? Thank you in advance for your assistance. <input type= ...

The 'getAllByRole' property is not found in the 'Screen' type. TS2339 error

I am currently developing a web application using ReactJs for the front end. While testing the code, I encountered the following error: TypeScript error in My_project/src/unitTestUtils.tsx(79,27): Property 'getAllByRole' does not exist on type & ...

Ways to customize background color for a particular date?

I have been using the fullcalendar npm package to display a calendar on my website. I am trying to figure out how to set a background color for a specific selected date. I tried looking into this issue on GitHub at this link. However, it seems that dayRe ...

Encountered a setback while constructing a library of Angular 7 components

While I successfully created a component library in Angular version 11 without any issues, I encountered an error when trying to build a component library in Angular version 7. Cannot find module 'tsickle/src/tsickle' Require stack: - D:\Ang ...

Unable to perform real-time transpilation of ES module, a loader plugin must be set up through the SystemJS.config configuration

I encountered an issue while trying to develop a plugable application. Everything was functioning correctly until I introduced "ngx-bootstrap" and "FullCalendarModule"/primeng in the plugin app. Importing any of these modules resulted in the following erro ...

Explaining the distinction between include and rootDir in tsconfig.json

According to the information provided, include defines an array of filenames or patterns that are to be included in the program during the compilation process. On the other hand, rootDir specifies the path to the folder containing the source code of the ap ...

What's the best way to show the calendar date in the mm-dd-yyyy format within an input search tag in Angular

I have implemented the <input class="input-group1 search" id="to" placeholder="dd-mm-yyyy" [(ngModel)]="toDate" value="" name="dp3" type="date"> in my code, which currently di ...

What is the best way to combine TypeScript output while maintaining node import integrity?

Currently, I am combining the results of the typescript compiler using this particular technique. However, this process is causing issues with the imports of relative path modules in Node. The code below compiles and merges successfully; // Group.ts clas ...

An issue with the animation script in Ionic

I'm having trouble converting this to an Ionic application. Here's my code sample. Can anyone help me with putting this code correctly in Ionic? I'm trying to achieve something like this example <script src="https://cdnjs.cloudflare.com ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...