【问题标题】:Nestjs TypeOrm postgresql using custom schemaNestjs TypeOrm postgresql 使用自定义模式
【发布时间】:2022-02-17 12:07:29
【问题描述】:

在我的 Nestjs TypeOrm 应用程序中,我想将我所有的数据库工件封装在一个名为 globe 的模式中。所以,我在ormconfig.ts中指明了架构

const DatabaseConfigForMigrations = {
  name: 'countrydb',
  type: 'postgres',
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  schema: 'globe',
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  synchronize: false,
  logging: true,
  entities: ['dist/src/**/*entity.js'],
  migrations: ['dist/src/migrations/**/*.js'],
  cli: {
    migrationsDir: 'src/migrations',
  },
  options: { trustServerCertificate: true },
};

也在我的模型中。比如;

@Entity({ schema: 'globe' })
@ObjectType()
export class City {
  @PrimaryGeneratedColumn()
  @Field(() => Int)
  id: number;

  @Column()
  @Field()
  name: string;

  @Column({ nullable: true })
  @Field({ nullable: true })
  touristic: boolean;

  @Column({ nullable: true })
  @Field(() => Int, { nullable: true })
  population: number;

  @ManyToOne(() => Country, (country) => country.cities)
  @JoinColumn({ name: 'country_id' })
  country: Country;

  @Column({ type: 'int', name: 'country_id' })
  countryId: number;
}

但是,不幸的是,当我运行yarn migration:run 时,error: error: schema "globe" does not exist 发生了。

如何让 TypeOrm 在我的 globe 架构中创建表?

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    必须显式使用 typeorm 的 url 连接选项,然后在其 search_path 选项中指定架构以使其为我工作,这有点棘手和奇怪。

    例如ormconfig.js

        module.exports = {
          type: 'postgres',
          url: `postgresql://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}?options=-c%20search_path=globe`,
          ...
    

    【讨论】:

    • 做不到。我还应该为每个模型明确设置架构吗?
    • 如果你能提供一个 github repo 示例,我将不胜感激 :-)
    • 除了 ormconfig.js + url 参数之外,我几乎拥有您上面所拥有的一切。还有一点,我正在使用: "typeorm": "^0.2.31",
    • 你能看一下吗? github.com/killjoy2013/graphql-nestjs 你可以通过 docker-compose up & yarn migration:run 试试看
    • 我认为您应该将以下行插入到行号中。 10 个 github.com/killjoy2013/graphql-nestjs/blob/06-auth/ormconfig.ts url: `postgresql://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}?options=-c%20search_path=globe`,
    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-06-07
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    相关资源
    最近更新 更多