I'm trying to make a nestjs project with Mikro Orm refrencing load-entities-automatically. But Mikro Orm does not create tables automatically... The following codes are my settings
AppModule.ts
@Module({
imports: [
MikroOrmModule.forRoot({
type: 'postgresql',
host: 'localhost',
user: 'test',
password: 'test',
dbName: 'test',
port: 5440,
autoLoadEntities: true,
entities: ['../entity/domain'],
entitiesTs: ['../entity/domain'],
allowGlobalContext: true,
schemaGenerator: {
createForeignKeyConstraints: false,
},
}),
UserModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
UserModule
@Module({
imports: [UserEntityModule],
controllers: [UserController],
providers: [UserService, UserRepository],
})
export class UserModule {}
UserRepository
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository } from '@mikro-orm/postgresql';
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserRepository {
constructor(
@InjectRepository(User)
private readonly userRepository: EntityRepository<User>,
) {}
async save(req: UserSaveRequest) {
const response = await this.userRepository
.createQueryBuilder()
.insert(req)
.execute();
return response;
}
}
UserEntityModule
import { MikroOrmModule } from '@mikro-orm/nestjs';
@Module({
imports: [MikroOrmModule.forFeature([User])],
exports: [MikroOrmModule],
})
export class UserEntityModule {}
User
import { Entity, Property } from '@mikro-orm/core';
@Entity({ tableName: 'users' })
export class User extends BaseEntity {
@Property({ comment: "user's nickname" })
nickname: string;
}
BaseEntity
export abstract class BaseEntity {
@PrimaryKey()
id: number;
}
Code is simple but too long... How can I solve it?
Few notes about what you are doing that might help:
MikroOrmModule
, the providers are automatically exported, this is not doing what you thinkallowGlobalContext: true
is there to allow unit testing mainly, you will fall into memory leaks and instable response issues if you use only the global context. you are doing it wrong if your app does not work without it.autoLoadEntities
is an alternative to the entities/entitisTs
options, don't mix them