【问题标题】:Typeorm - Cannot update entity because entity id is not set in the entityTypeorm - 无法更新实体,因为实体中未设置实体 ID
【发布时间】:2021-08-01 04:16:36
【问题描述】:

我正在尝试在我的数据库中保存(插入)一条新记录,但我得到的只是错误:Cannot update entity because entity id is not set in the entity.

我目前在做什么:

return this.connection.transaction(entityManager => {
   return entityManager.save(MyEntity, {/* payload without id */});
});

这是我的代码库中唯一发生此问题的地方(交易与否)

【问题讨论】:

标签: mysql node.js typescript nestjs typeorm


【解决方案1】:

TypeORM 跟踪具有元数据的实体,并且很可能 id 仍在元数据中或已进入元数据。要解决这个问题,请通过 create 函数。

return this.connection.transaction(entityManager => {
   // make sue payload is at this point already without id field else your problem will remain
   const entity = entityManager.create(payload)
   return entityManager.save(MyEntity, entity);
});

您很可能正在使用获取的实体作为模板,删除了 id,可能还有其他一些设置,然后再次尝试保存。

即使这可能不是您得到此错误的确切方式。我看到这个错误发生时最常发生。

【讨论】:

  • 我认为你是对的,我的问题解释得太简单了。我确实使用了 create 方法,但仍然无法使其工作。我正在使用来自类验证器的有效负载,我假设这些元数据一定会干扰来自 typeorm 的有效负载。为了解决我的问题,我重建了我的项目(docker、dist、一切)。感谢您的解释@Funonly
猜你喜欢
  • 2018-09-10
  • 2019-02-08
  • 1970-01-01
  • 2015-11-08
  • 2012-04-15
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多