简体   繁体   中英

Cannot use TypeOrm with express “connection ”Default" not found

I'm currently having a bad time with typeOrm, I don't know why but express is getting initialized before my connection to the database with typeOrm So I get an error "Connection default not found"

here's the code

Typeorm.config.ts

import {Connection, createConnection} from 'typeorm';

export function connectToDb(): Promise<Connection> {
    return createConnection({
        type: 'postgres',
        url: process.env.TYPEORM_URL,
        synchronize: false,
        logging: true,
        entities: [process.env.TYPEORM_ENTITIES],
        migrations: ["../../migrations/*.ts"],
        cli: {migrationsDir: process.env.TYPEORM_MIGRATIONS_DIR}
    })
}

Room.repository

import {getRepository} from 'typeorm';
import {Room} from '../entities/Room';

const roomRepository = getRepository(Room)

export async function getAllRooms(): Promise<Room[]> {
    return await roomRepository.find()
}

this repo is used by my router, here's my app.ts

import * as express from 'express'
import * as bodyParser from 'body-parser';
import * as PassportJs from './passport';
import cors from 'cors';
import logger from './config/logger';
import "reflect-metadata";
import * as dotenv from 'dotenv';

dotenv.config();

import roomRouter from './routes/room.route';
import {connectToDb} from './config/typeorm.config';
const passport = PassportJs.initPassport();

async function main(): Promise<void> {

    logger.info('connecting to database...')
    await connectToDb()
    logger.info('connected to database')

    const app = express();
    app.use(bodyParser.json());
    app.use(passport.initialize());
    app.use(cors());

    app.use(roomRouter);

    app.listen(3000, () => {
        logger.info(`API is running on port ${3000}`);
    });
}
main().catch(error => {
    logger.error(error)
    process.exit(1)
})


Can you help me?

Thank

From the code snippets you have share, I guess const roomRepository = getRepository(Room) is being called before the await connectToDb() . Creating a repo needs connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM