mikro-orm Cascade.REMOVE,它只适用于 RDBMS 吗?

mikro-orm Cascade.REMOVE, is it only for RDBMS?

我正在将 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);
    }
}

"business" 已正确删除,但所有相关 "locations" 继续存在。

日志只显示:

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

级联在应用程序级别工作,因此适用于所有驱动程序,包括 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 删除的方法才有效。