我正在使用 mikro-orm 和 MongoDB 并尝试做一个 Cascade.MOVE,但我无法让它工作。
商业实体:
@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(( [taken 0 ms]
Cascades 在应用程序级别工作,因此适用于所有驱动程序,包括 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 删除的方法才有效。