1

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

“业务”被正确删除,但所有相关的“位置”继续存在。

日志只显示:

[查询记录器] db.getCollection("business").deleteMany() [耗时 0 毫秒]

4

1 回答 1

1

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

这里的问题是您正在Business按 id 删除实体。您需要通过引用将其删除 - 提供实体并确保您已填充集合,否则 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 删除的方法才有效。

于 2019-04-10T10:34:15.257 回答