写在前面
Today,在开发环境可以正常运行 typeorm 并且找到实体类,但是一打包生产环境用 pm2 运行就不行了,报错如下:
No repository for “UserInfo” was found. Looks like this entity is not
registered in current “default” connection
零
先看看是不是实体类上面没有加 @Entity 注解!
如下所示
/**
* AvatarInfo Entity
*/
import { Entity, Column } from 'typeorm';
import { BaseEntity } from './BaseEntity';
@Entity({ name: 'tb_avatar_info' }) // <<< === 切记加上注解!
export class AvatarInfo extends BaseEntity {
@Column({ name: 'user_id' })
userId: string;
@Column({ name: 'file_id' })
fileId: string;
@Column({ name: 'status' })
status: number;
}
解决方案
-
首先观察我的项目目录结构
如下图,生成后的 dist 位于根目录下,所以 build 的 时候 entities 的位置需要从根目录开始拼写!
-
找到项目下的 ormconfig.js,作如下修改(如果你是 json,请改成 js)
const env = process.env.NODE_ENV;
module.exports = {
type: 'mysql',
host: 'your database ip',
port: your_port,
username: 'your_username',
password: 'your_password',
database: 'your_database',
synchronize: false,
// 根据你实体类文件夹实际地址填写
entities: [`${env === 'development' ? 'src/' : 'dist/src/'}entity/*{.js,.ts}`]
};
- 重新打包并运行,解决!
项目地址
- Koa + Typescript + typeorm 起手架子:https://github.com/supervons/PreheatingKoa
- 示例轮子项目:https://github.com/supervons/ExploreKoa