【问题标题】:mikro-orm Cascade.REMOVE, is it only for RDBMS?mikro-orm Cascade.REMOVE,是否仅适用于 RDBMS?
【发布时间】:2019-04-10 18:34:15
【问题描述】:

我正在将 mikro-orm 与 MongoDB 一起使用并尝试执行 Cascade.REMOVE,但我无法让它工作。

企业实体:

@Entity({ collection: "business" })
export class BusinessModel implements BusinessEntity {
    @PrimaryKey()
    public _id!: ObjectId;

    @Property()
    public name!: string;

    @Property()
    public description!: string;

    @OneToMany({ entity: () => LocationModel, fk: "business", cascade: [Cascade.ALL] })
    public locations: Collection<LocationModel> = new Collection(this);
}

export interface BusinessModel extends IEntity<string> { }

位置实体:

@Entity({ collection: "location" })
export class LocationModel implements LocationEntity {
    @PrimaryKey()
    public _id!: ObjectId;

    @Property()
    public geometry!: GeometryEmbedded;

    @ManyToOne({ entity: () => BusinessModel})
    public business!: BusinessModel;

    public distance?: number;
}

export interface LocationModel extends IEntity<string> { }

业务数据:

_id: 5cac818273243d1439866227
name: "Prueba"
description: "Prueba eliminacion"

位置数据:

_id: 5cac9807179e380df8e43b6c
geometry: Object
business: 5cac818273243d1439866227

_id: 5cacc941c55fbb0854f86939
geometry: Object
business: 5cac818273243d1439866227

还有代码:

export default class BusinessData {
    private businessRepository: EntityRepository<BusinessModel>;

    public constructor(@inject(OrmClient) ormClient: OrmClient) {
        this.businessRepository = ormClient.em.getRepository(BusinessModel);
    }

    public async delete(id: string): Promise<number> {
        return await this.businessRepository.remove(id);
    }
}

“企业”已正确删除,但所有相关“位置”仍保留在那里。

日志只显示:

[query-logger] db.getCollection("business").deleteMany() [耗时 0 ms]

【问题讨论】:

  • 只是好奇 - 你真的从查询记录器中得到了这个,还是你删除了 where 部分?如果是这样,您确定要为 id 参数提供值吗?
  • 不,我没有删除 where 部分,我为 id 参数提供了值。将代码更改为:public async delete(id: string): Promise&lt;number&gt; { // tslint:disable-next-line: no-console console.log(id); return await this.businessRepository.remove(id); } 这是实体发现后的输出,不删除任何内容:5cac818273243d1439866227 [query-logger] db.getCollection("business").deleteMany() [took 0 ms]
  • 刚查了代码,只在查询记录器中丢失,查询数据库时没有省略条件。会尽快解决的,看起来很吓人:]

标签: mikro-orm


【解决方案1】:

级联在应用程序级别上工作,因此适用于所有驱动程序,包括 mongo。

这里的问题是您正在通过 id 删除 Business 实体。您需要通过引用将其删除 - 提供实体并确保您已填充集合,否则 ORM 不知道要级联删除哪些实体。

试试这样:

export default class BusinessData {
  public async delete(id: string): Promise<number> {
    const business = await this.businessRepository.findOne(id, ['locations'])
    return await this.businessRepository.remove(business);
  }
}

仅当实体已加载到身份映射(又名由 EM 管理)中(包括 locations 集合)中时,您的按 id 删除方法才有效。

【讨论】:

  • 是的,它正在工作。谢谢(我希望我不会太讨厌)
  • 绝对不是!谢谢你的好问题!我将在不久的将来根据这些问题制作一个常见问题解答页面。
猜你喜欢
  • 2021-11-13
  • 1970-01-01
  • 2022-01-09
  • 2021-02-08
  • 2021-08-30
  • 2021-04-23
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多