首页 > 解决方案 > Mikro-ORM 即使在停用时仍然存在级联

问题描述

我的实体关系一定有问题,因为每当我尝试将父实体及其子实体持久化时,Mikro-ORM 也会不断尝试持久化子实体,即使给定属性的级联已停用。

我有一些音乐会:

import { Entity, PrimaryKey, Property, SerializedPrimaryKey, Collection, ManyToMany } from "@mikro-orm/core";
import { ObjectId } from 'mongodb';
import { Artist } from "./artist";

type Props = {
    readonly _id: ObjectId;
    readonly artists?: Collection<Artist>;
}

@Entity()
export class Concert {
    constructor(private props: Props) { Object.assign(this, props) }

    /* Private variables */
    @PrimaryKey()
    readonly _id!: ObjectId;

    @SerializedPrimaryKey()
    id!: string; // won't be saved in the database

    @ManyToMany({ entity: () => Artist, mappedBy: 'concerts', cascade: [] }) // cascading should be deactivated
    public readonly artists = new Collection<Artist>(this);
}

和一些艺术家:

import { Entity, PrimaryKey, Property, SerializedPrimaryKey, Collection, ManyToMany, Cascade, OneToMany } from "@mikro-orm/core";
import { ObjectId } from 'mongodb';
import { Concert } from "./concert";
import { User } from "./user";

type Props = {
    readonly _id: ObjectId;
    readonly concerts?: Collection<Concert>;
    readonly name: string;
}

@Entity()
export class Artist {
    constructor(private props: Props) { Object.assign(this, props) }

    /* Private variables */
    @PrimaryKey()
    readonly _id!: ObjectId;

    @SerializedPrimaryKey()
    id!: string; // won't be saved in the database

    @ManyToMany({ entity: () => Concert, mappedBy: 'artists', cascade: [], owner: true }) // cascading should be deactivated
    public readonly concerts = new Collection<Concert>(this);

    @Property()
    public readonly name!: string;
}

我已经有一个艺术家保存在我的 mongodb 数据库中,在artist带有示例 ObjectId 的集合 下_id : ObjectId("a")

当试图像这样坚持时:

const concert = new Concert({ _id: new ObjectId() });

concert.artists.add(new Artist({ "_id": new ObjectId("a"), "name": "" })) 

await concertRepository.persistAndFlush(concert)

我收到以下消息:

UniqueConstraintViolationException: E11000 duplicate key error collection: db.artist index: _id_ dup key: { _id: ObjectId('a') }

有谁知道我做错了什么?

标签: mongodbmikro-orm

解决方案


所以我发现了我出错的地方,像这样添加艺术家:

concert.artists.add(new Artist({ "_id": new ObjectId("a"), "name": "" })) 

只是不会削减它。要添加现有艺术家,请按以下步骤操作:

// Use the mikro-orm findOne method from the entity manager
const artist = await artistRepository.findOne(Artist, { _id: new ObjectId('a') })
// Add it to the collection
if (artist) concert.artists.add(artist);
// Now I can persist the concert and the artist is not duplicated
await concertRepository.persistAndFlush(concert)

推荐阅读