I just started using typescript, and have been trying to learn how to use TypeORM on the backend.
I started coding a CRUD API using typeORM and postgreSQL, after I made all the initial setup configuration I ran the application, but the TypeORM is not creating my User entity on the database.
Here is what my code looks like:
- data-source.ts file:
import * as dotenv from 'dotenv';
import { DataSource } from "typeorm"
import { User } from "./entity/User"
dotenv.config();
export const AppDataSource = new DataSource({
type: "postgres",
host: process.env.TYPEORM_HOST,
port: 5432,
username: process.env.TYPEORM_USER,
password: process.env.TYPEORM_PASSWORD,
database: process.env.TYPEORM_DATABASE,
logging: false,
entities: [User],
migrations: [],
subscribers: [],
synchronize: true,
});
- app.ts file:
import express from 'express';
import { AppDataSource } from "./db/data-source";
class App {
public express: express.Application
public constructor() {
this.express = express();
this.middlewares();
this.routes();
this.datababase();
};
private middlewares(): void {
this.express.use(express.json());
};
private routes(): void {
this.express.get('/teste', (_req, res) => res.send('api rodando'));
};
private async datababase(): Promise {
await AppDataSource.initialize().then(async () => console.log('connected')).catch(error => console.log(error.message));
};
}
export default new App().express;
- my User.ts entity file (PS: the import is obviously part of the file but the stack overflow editor straight up refuses to place it inside the code block no matter what I do):
{ import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity('users')
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
email: string
@Column()
password: string
};
I expected that by the moment I ran the application the User table would be created automatically since I passed the tag synchronize on the data-source.ts file, and referenced the User entity as well. But nothing happens when I run the application.
Note that the "connected" message shows up on my console when the initialize
method is called at the database
method in my App class, which indicates to me that the initialization is working fine.
PS: I apologize for the inconsistence of the code blocks, but I really can't figure out the stack overflow text editor, I am absolutely NEVER able to make this thing work properly.
1条答案
按热度按时间oprakyz71#
请尝试
@Entity({name: "users"})
而不是@Entity('users')
您可以选择使用这些其他选项
@Entity({name: "users", schema: "public", synchronize: true})