即使停用,Mikro-ORM 仍会持续级联

Mikro-ORM still cascades while persisting even when deactivated

我一定是在我的实体关系上做错了什么,因为每当我尝试持久化父实体及其子实体时,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') }

有谁知道我做错了什么吗?

所以我找到了错误的地方,像这样添加艺术家:

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)

如果不想加载艺术家,可以使用em.getReference():

concert.artists.add(artistRepository.getReference('a'));
await concertRepository.persistAndFlush(concert);

还要注意,如果这里的concert实体已经被管理(从数据库加载),你可以调用em.flush(),不需要再次持久化它(EM已经知道了) .