One potential solution for fixing the error in GetRepository of TypeORM is to check for undefined properties before attempting to access them. This error typically occurs when trying to read properties of an undefined

[Nest] 171 - 08/31/2022, 8:35:42 PM ERROR [ExceptionHandler] Cannot read properties of undefined (reading 'getRepository') tenant-node | TypeError: Cannot read properties of undefined (reading 'getRepository') tenant-node | at InstanceWrapper.useFactory [as metatype] (/var/www/app/src/infrastruture/providers/tenant.provider.ts:6:56) tenant-node | at Injector.instantiateClass (/var/www/app/node_modules/@nestjs/core/injector/injector.js:343:55) tenant-node | at callback (/var/www/app/node_modules/@nestjs/core/injector/injector.js:53:45) tenant-node | at processTicksAndRejections (node:internal/process/task_queues:95:5) tenant-node | at Injector.resolveConstructorParams (/var/www/app/node_modules/@nestjs/core/injector/injector.js:132:24) tenant-node | at Injector.loadInstance (/var/www/app/node_modules/@nestjs/core/injector/injector.js:57:13) tenant-node | at Injector.loadProvider (/var/www/app/node_modules/@nestjs/core/injector/injector.js:84:9) tenant-node | at async Promise.all (index 3) tenant-node |
at InstanceLoader.createInstancesOfProviders (/var/www/app/node_modules/@nestjs/core/injector/instance-loader.js:47:9) tenant-node | at /var/www/app/node_modules/@nestjs/core/injector/instance-loader.js:32:13

Content in my tenant.provider.ts:

import { DataSource, getRepository, Repository } from "typeorm";
import { TenantSchema } from "../db/TenantSchemas.schema";

export const TenantProviders = [{
    provide: 'TENANT_REPOSITORY',
    useFactory: (dataSource: DataSource) => dataSource.getRepository(TenantSchema),
    Inject: ['DATA_SOURCE']
}, ];

Inclusion within my app.module.ts:

    import { Module } from '@nestjs/common';
    import { ConfigModule } from '@nestjs/config';
    const envTenant = ConfigModule.forRoot({
      isGlobal: true
    })
    import { TenantModule } from './tenant.module';
    import { TenantProviders } from '../infrastruture/providers/tenant.provider';
    import { TenantTypeOrmRepository } from '../infrastruture/db/TypeOrmRepository';
    import { DBTenant } from '../infrastruture/db/connections/db.tenant';
    import { TenantController } from './tenant.controller';
    
    @Module({
      imports: [
        envTenant,
        DBTenant,
        //TenantModule
      ],
      controllers: [TenantController],
      providers: [
        ...TenantProviders,
        TenantTypeOrmRepository
      ],
    })
    export class AppModule {}

My TenantSchema.schema.ts:
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class TenantSchema {
    constructor(tRepository?: Partial<TenantSchema>) {
        this.id = tRepository?.id;
        this.name = tRepository?.name;
        this.tenant = tRepository?.tenant;
        this.isActive = tRepository?.isActive;
    }

    @PrimaryGeneratedColumn()
    id: number;

    @Column({ length: 128 })
    name:string;

    @Column({ length: 10 })
    tenant:string;

    @Column({ default: false })
    isActive:boolean;
}

Database provider setup in db.provider.ts

import { appDataSource } from './app.source';

export const dbProviders = [
  {
    provide: 'DATA_SOURCE',
    useFactory: async () => {
      return appDataSource.initialize();
    },
  },
];

Answer №1

Dealing with a similar issue recently led me to a helpful discovery:

I had inadvertently assigned the identical PORT number to my Express and Data-Source, causing both to conflict when attempting to connect at PORT 3000 simultaneously. Once I reassigned Express to 3000 and Data-Source to 5432, all functionality was restored.

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

PHP: I am unable to establish a connection with the script or submit form data to mySQL

Seeking assistance with debugging this script. (The * represents confidential information that I am aware of but cannot share) <?php $dbhost = '*********'; $dbuser = '*********'; $dbpass = '*********'; $conn = mysql_conne ...

Searching for variables within files using Node.js and constructing an object from the results

Trying to figure out how to streamline this process. Here's the directory structure I'm working with: src/ modules/ clients/ i18n/ en-US.ts tasks/ i18n/ en-US.ts So, ea ...

This SQL query is restricted from crossing a 'year end' boundary

In the context of downloading an .xlsx file through a Smarty File, this SQL code functions well for all months except December (the end of the year). There seems to be a requirement for it to smoothly cross over the year-end boundary, yet the specific so ...

What is the best way to choose a random ID from a table within specified time intervals in MySQL?

I need to retrieve a random ID from the table nodes within the last 15 seconds. I attempted the following code, but it produced a lengthy output: const mysql = require('mysql'); const connection = mysql.createConnection({ host ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

Creating Your Own Custom Select with DataTables

Hey there! I’m currently utilizing the tablesorter-plugin DataTables with serverside processing and ajax pipelining. Here’s a glimpse of my present serverside script: <?php // Database table being used $tabl ...

Using Python to iterate through a list and pass it as parameters in a MySQL query with a FOR loop

Trying to loop through a Python list for multiple queries in MySQL, but facing issues with the quotes included in the "%s" parameter resulting in only zeros (0) being returned instead of the expected numbers. The code snippet is as follows: def expor ...

Angular ReactiveForms not receiving real-time updates on dynamic values

I'm using reactive forms in Angular and I have a FormArray that retrieves all the values except for product_total. <tbody formArrayName="products"> <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i"> ...

Search through an array of objects and assign a new value

I am facing a challenge with an array of objects structured as shown below: [ { "e_id": "1", "total": 0 }, { "e_id": "3", "total": 0 } ] My objecti ...

Vue.js and TypeScript combination may result in a 'null' value when using file input

I am attempting to detect an event once a file has been uploaded using a file input. Here is the JavaScript code: fileSelected(e: Event) { if ((<HTMLInputElement>e.target).files !== null && (<HTMLInputElement>e.target).files[0] !== null) { ...

Looking for a solution to resolve the issue "ERROR TypeError: Cannot set property 'id' of undefined"?

Whenever I attempt to call getHistoryData() from the HTML, an error message "ERROR TypeError: Cannot set property 'id' of undefined" appears. export class Data { id : string ; fromTime : any ; toTime : any ; deviceType : string ...

Is it possible to leverage Spring profiles in order to load varying datasets in data.sql based on the environment?

https://i.sstatic.net/DCU0Y.png Imagine having two different sets of data, One set is for production, while the other is for development. Currently, I am manually switching between the two by commenting and uncommenting in the data.sql file. What is the ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

How to retrieve a value from a base64-decoded string in Angular 6?

I successfully decoded a Base64 string using the xml2js library and obtained the following XML value: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="293" height="102" viewBox="0 0 293 102" xmlns="http://www.w3.org/2000/svg" ...

What is the best way to define multiple variables in ionic 2 using Angular2 and TypeScript?

I'm brand new to working with ionic2/Angular2/Typescript. My project involves creating a wheel with eight slices, but I'm struggling with how to declare multiple variables. In JavaScript, I've declared them like this: function rand(min, max ...

PHP with automatic commit

My code attempts to disable AutoCommit in PHP: <?php $con = mysqli_connect("localhost","root","","databases"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(mysqli_query($con,"SET autocommit=0")){ ...

How can you create a function in typescript that only allows parameters of a specific type?

Here's what I'm trying to accomplish: function validateNumber(param: ???): param is number { } If the parameter can be a number, such as number | string or number | boolean, it should be accepted by the function. However, if the type is somethin ...

Utilizing Subquery Results from MySQL in Parent WHERE Clause

At our school, students are rewarded with virtual currency (either a pound or a dollar) for good behavior. This currency is stored in a database. Here is the query I am using: SELECT s.chosen_name, s.chosen_surname, s.regId, s.admission_number, ( ...

Is it possible for SQL to provide information on various conditions assessed in a single query, or would it be more efficient to split them into

As I develop my code, I am faced with a decision regarding how to structure my SQL queries for testing multiple conditions. Should I create a single multipart MySQL query or opt for individual queries and let PHP handle the logic of combining them? This di ...

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...