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

时间:2019-04-10 10:21:04

标签: mikro-orm

我正在将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毫秒]

1 个答案:

答案 0 :(得分:0)

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