Skip to content
Advertisement

TypeORM fails to connect without any error message

I am trying to get started with TypeORM, but cannot get createConnection to work. I run the default tpyeorm init server file, but there is not error or logging shown, nor is the postgres DB updated.

index.ts

import "reflect-metadata";
import {createConnection, ConnectionOptions} from "typeorm";
import {User} from "./entity/User";
import * as ormconfig from '../ormconfig.json';

console.log("is the file called correctly?");

createConnection(ormconfig as ConnectionOptions).then(async connection => {//ive also tried removing this 'async' keyword, but that doesnt help

    console.log("Inserting a new user into the database...");
    const user = new User();
    user.firstName = "Timber";
    user.lastName = "Saw";
    user.age = 25;
    await connection.manager.save(user);
    console.log("Saved a new user with id: " + user.id);

    console.log("Loading users from the database...");
    const users = await connection.manager.find(User);
    console.log("Loaded users: ", users);

    console.log("Here you can setup and run express/koa/any other framework.");

}).catch(error => console.log(error));

console.log('is this code reached?')

ormconfig.json (note: I changed the postgres password to ‘root’)

{
   "type": "postgres",
   "host": "localhost",
   "port": 5432,
   "username": "postgres",
   "password": "root",
   "database": "mhfit",
   "synchronize": true,
   "logging": true,
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "src/migration",
      "subscribersDir": "src/subscriber"
   }
}

running start gives the following output:

> mhfit-server@0.0.1 start /home/james/Documents/mhfit/mhfit-server
> ts-node src/index.ts

is the file called correctly?
is this code reached?

Note that none of the other logging statements are hit. Why is that? Neither are errors shown.

postgres databases on my local machine:

User$ sudo -i -u postgres
'postgres@user:~$ psql
postgres=# list
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 mhfit     | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(4 rows)

The default User table is not created after trying to start the server

postgres-# c mhfit
You are now connected to database "mhfit" as user "postgres".
mhfit-# dt
Did not find any relations.

Update

I followed and downloaded the code from this tutorial, and magically it worked. But unfortunately my old project still failed…

Eventually I tried messing with my models, and discovered that the failure was due to TypeORM not liking how I setup some of my models. I have a model, A that can have two arrays of model B (Bs that exist before event A, and Bs that exist after event A).

In TypeORM I had set this up to be 2 OneToMany relationships on A, and 2 ManyToOne relatonships on the B class. Something about this crashed TypeORM though. What is the correct way to do this instead?

A:

...
@OneToMany(type => B, preB => preB.preA)
preBs: B[];
@OneToMany(type => B, postB => postB.postA)
postEmotions: B[];

B:

...
@ManyToOne(type => A, preA => preA.preBs)
preA: A;
@ManyToOne(type => A, postA => postA.postBs)
postA: A;

Advertisement

Answer

In the update I say that it failed to start due to an Entity setup issue. Entity A can have many Bs, both before and after an event. I ended up getting it working by setting up the Entities as so:

//added this class just for fun
@InterfaceType()//TypeGraphQL stuff
export abstract class ParentEntity extends BaseEntity {
    @Field(type => ID)//TypeGraphQL stuff
    @PrimaryGeneratedColumn() public id: number;

    @Field()
    @CreateDateColumn() public createdAt: Date;

    @Field()
    @UpdateDateColumn() public updatedAt: Date;
}


@InterfaceType({ implements: ParentEntity }) //TypeGraphQL stuff
export abstract class B extends ParentEntity { //Notice this is an abstract class now
    @Field()//TypeGraphQL stuff
    @Column({
        type: "varchar",
        length: 100,
        nullable: true
    })
    myField: string;
}

@Entity()
@ObjectType({ implements: B })//TypeGraphQL stuff
export class PostB extends B {
    @ManyToOne(type => A, postB => postB.A)
    myA: A;
}


@Entity()
@ObjectType({ implements: B })
export class PreB extends B {
    @ManyToOne(type => A, PreB => PreB.A)
    myA: A;
}


@Entity()
@ObjectType({ implements: ParentEntity })
export class A extends ParentEntity {
    @OneToMany(type => PreB, bPre => bPre.myA)
    preBs: PreB[];
    @OneToMany(type => PostB, bPost => bPost.myA)
    postBs: PostB[];
}

I also had to update my TypeORM package…

Edit: Duplicating your entities causes double the work when creating resolvers, seeders, and when querying on the front end. An easier way is to add a ‘Type’ enum field/column on the entity.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement