Once the table is created in TypeORM, make sure to insert essential master data such as types and statuses

Hey there, I have a question regarding NestJS and typeORM. My issue is with inserting default values into tables after creating them. For example, I have a priority table where I need to insert High/Medium/Low values. Despite trying everything in the typeorm and NestJS documentation, as well as reading related questions on various forums, I still haven't been successful.

import {getConnection} from "typeorm";

await getConnection()
    .createQueryBuilder()
    .insert()
    .into(User)
    .values([
        { firstName: "Timber", lastName: "Saw" }, 
        { firstName: "Phantom", lastName: "Lancer" }
     ])
    .execute();

I came across the code above and believe this might be the solution. However, I'm uncertain about which file to add this code chunk to. Any guidance provided will be greatly appreciated. Thank you!

Answer №1

Utilizing migrations is a great way to ensure your database remains current. These migrations are not limited to just altering tables; they can also be used to insert default data. TypeORM offers a handy tool for this purpose.

Answer №2

One method I use for this task is through migrations. By writing a static query or importing data from a CSV file and saving it to the database in a loop.

To start, you can create an empty migration with the command

npx typeorm migration:create -n InsertMasterDataInDB

Next, you can utilize the following query to insert the data:

await queryRunner.manager.query(INSERT QUERY HERE IN SINGLE QUOTES);

Lastly, run the migration using npx typeorm migration:run

Answer №3

When it comes to migrating your data in a database, using seeders is essential for populating your tables with the necessary information once the migration process is completed.

To make this task easier, I highly suggest utilizing the typeorm-seeding package.

It's important to keep your migrations focused solely on changes to the database structure, while separating out the seeding of actual data as much as possible for better organization.

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

WebSocket connection outbound from Docker container fails to establish

Running a TypeScript program on Docker that needs to open a Websocket connection to an external server can be a bit tricky. Here is the scenario: ----------------------- ------------------------------ | My Local Docker | ...

No declaration file was located for the module '@handsontable/react' despite the presence of a 'd.ts' file

Embarking on a fresh project using vite+react+ts+swc by executing the command below as per the vite documentation. npm create vite@latest -- --template react-swc-ts Additionally, I integrated the handsontable library into my setup with the following comm ...

Updated the application to Angular 6 but encountered errors when attempting to run npm run build --prod. However, running the command npm run build --env=prod was executed without any issues

Running the command npm run build -- --prod results in the following error messages: 'PropertyName1' is private and can only be accessed within the 'AppComponent' class 'PropertyName2' does not exist in type 'AppCompo ...

Encountering a 500 (Internal Server Error) while attempting to fetch a single document from MongoDB without utilizing the

I am currently developing my first project using the MEAN stack, and I'm facing a challenge with retrieving a single element from MongoDB. The specific page I'm working on is meant to allow users to edit an item from a list displayed on the main ...

Enigmatic Cartography Classification

In my attempt to construct a specialized Map-like class that maps keys of one type to keys of another, I encountered a challenge. A straightforward approach would be to create a Map<keyof A, keyof B>, but this method does not verify if the member typ ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

Tips for hiding a sidebar by clicking away from it in JavaScript

My angular application for small devices has a working sidebar toggling feature, but I want the sidebar to close or hide when clicking anywhere on the page (i.e body). .component.html <nav class="sidebar sidebar-offcanvas active" id="sid ...

In TypeScript, a mapped type is not allowed to define properties or methods

My challenge involves defining an interface with keys that match a specific enum key type. However, when I attempt to declare this type, I encounter the following error message: A mapped type may not declare properties or methods. Below is the code snip ...

Using Typescript: Generate keys in function return depending on parameter

Currently in the process of developing an SDK for a Rest API that includes an embed request parameter to fetch additional resources and add them to the response. I am exploring if there is a way, using Typescript, to extract these embed parameters while de ...

Adjust the property to be optional or required depending on the condition using a generic type

const controlConfig = >T extends 'input' | 'button'(config: Config<T>): Config<T> => config; interface Config<TYPE extends 'input' | 'button'> { type: TYPE; label: string; ...

Does JSX/TSX markup act as a constant that is passed by value or by reference?

In a separate file called EmptyNode.tsx, I have defined a constant: export const EmptyNode = <></> This constant is used to return an empty node when there is no content to display. For example: ... render() { if(!this.props.data) { ...

Transferring data types to a component and then sending it to a factory

I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error: error TS1005: ',' expected. The issue arises when I try to pa ...

The (change) function is triggered when there is a modification in the parent object of ngModel within Angular 2

When the (change) function on element is triggered with the parent object of ngModel change in Angular 2, this is how I assigned the model: (change)="OnScheduleChange(confirmSchedule)" [(ngModel)]="AddMedMod.schedule.numberOfDaysOn" Now, whenever I make ...

What is the best way to make the current year the default selection in my Select control within Reactive Forms?

Hey there! I managed to create a select element that displays the current year, 5 years from the past, and 3 years from the future. But now I need to figure out how to make the current year the default selection using Reactive Forms. Any ideas on how to ac ...

Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option u ...

What is the reason for a boolean extracted from a union type showing that it is not equivalent to true?

I'm facing a general understanding issue with this problem. While it seems to stem from material-ui, I suspect it's actually more of a typescript issue in general. Despite my attempts, I couldn't replicate the problem with my own types, so I ...

The angular-CLI does not support the use of content delivery networks (CDNs) within the .angular-cli.json

Is there a way to make angular-cli recognize when we add any deployed URLs for styles or scripts using CDN? Currently, adding them to index.html works but adding to .angular-cli.json has no effect. Any workaround available? ...

TypeScript: Defining a custom object type using an array of objects

Is there a way to dynamically generate an object based on the name values in an array of objects? interface TypeA { name: string; value: number; } interface TypeB { [key: string]: { value: any }; } // How can we create an OutputType without hard ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

Require assistance in accurately assigning a date to a Date[] in Typescript Array without altering current elements

In my current code, I have a loop that verifies if a date is a holiday and then adds it to an array. The issue I'm facing is that whenever I assign a new element to the array, all previous data in the list gets updated to the latest element. Here&apos ...