【问题标题】:TypeORM database is always empty after restartTypeORM 数据库重启后始终为空
【发布时间】:2021-12-14 17:37:29
【问题描述】:

我刚开始使用 typeorm,遇到了一个大问题。 conection.sychronize()repository.save(foo) 实际上都不会保存对数据库文件的更改。更确切地说,在运行期间我可以同步我的数据库,保存和读取实体就好了。但是,当我关闭我的程序并再次运行它时,数据库是空的。连桌子都没有。

我的实体

@Entity({name: "info"})
export class DBInfo {
  @PrimaryGeneratedColumn()
  id: number;

  @Column("integer", { name: "gameCreation", unique: true })
  gameCreation: number;

  @Column("integer", { name: "gameDuration"})
  gameDuration: number;

  @Column("integer", { name: "gameId", unique: true })
  gameId: number;
}

@Entity({name: "match"})
export class DBMatch {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToOne(() => DBInfo, {cascade: true})
  @JoinColumn()
  info: DBInfo;
}

我这样打开连接

let connectionTemp: Connection;
try{
  connectionTemp = await createConnection({
    type: "sqljs",
    location: filePath,
    entities: [DBMatch, DBInfo],
    name: "MyConnection1"
  });
  console.log("DBReader", "connection open");
} catch (e){
  console.log("DBReader", "could not open connection", e);
}

return connectionTemp;

然后我同步数据库,创建所有表:

await this.connection.synchronize(false);

像这样将实体写入数据库:

let savedMatch = await this.MatchRepositoryV5.save(dbMatch);

我留下了部分代码,因为我认为它没有必要。

之后我可以从数据库中检索匹配项,但是当重新启动我的程序时,数据库再次完全为空。 我错过了什么?

【问题讨论】:

  • 你是在 Docker 中运行这个吗?
  • @AmbassadorKosh no

标签: typescript typeorm mysqljs


【解决方案1】:

您需要将autoSave连接属性设置为true

所以你初始化连接如下:

let connectionTemp: Connection;
try{
  connectionTemp = await createConnection({
    type: "sqljs",
    location: filePath,
    autoSave: true,
    entities: [DBMatch, DBInfo],
    name: "MyConnection1"
  });
  console.log("DBReader", "connection open");
} catch (e){
  console.log("DBReader", "could not open connection", e);
}

return connectionTemp;

【讨论】:

    猜你喜欢
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多