我的实体关系一定有问题,因为每当我尝试将父实体及其子实体持久化时,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') }
有谁知道我做错了什么?