无法从1:1关系的反面访问引用



我有以下两个实体(当然为了简化问题(:

用户的

@Entity({ collection: "users" })
export class User {
@PrimaryKey()
_id!: ObjectId;
@SerializedPrimaryKey()
id!: string;
/** The class the user is classmaster of */
@OneToOne({ inversedBy: "classmaster", orphanRemoval: false })
lead_class?: Reference<Class>;
}

分类.ts

@Entity({ collection: "classes" })
export class Class {
@PrimaryKey()
_id!: ObjectId;
@SerializedPrimaryKey()
id!: string;
/**
* Classmaster
* - 'null' if the class does not have an assigned classmaster.
*/
@OneToOne({ mappedBy: "lead_class" })
classmaster?: Reference<User>;
}

我可以从用户端访问类引用,但不能从类端访问classmaster(用户引用(。我也尝试过填充,但没有成功。如何从反面访问用户?这不可能吗?下面是一个示例代码:

let c = await db.classes.findOneOrFail(
{ id: "example_id" },
{ strict: true, populate: ["classmaster"] }
);
console.log("Classmaster: ", c.classmaster); // prints out undefined

不幸的是,这无法通过填充提示实现。在SQL驱动程序中,这种确切的情况是通过自动加入拥有方来解决的,以了解FK,但由于mongo没有加入,我们真的无法做到这一点。尽管通过CCD_ 1来实现这一点是一个很好的实验。

相反,您可以直接查询拥有实体,并将其分配给relation属性。类似这样的东西:

let c = await db.classes.findOneOrFail("example_id");
c.classmaster = await db.classmasters.findOne({ class: c.id });
console.log("Classmaster: ", c.classmaster);

最新更新