typescriptmongodbdatabase-schemadatabase-relationsmikro-orm

Cannot access reference from inverse side of a 1:1 relationship


I have the following two entities (simplified for the question of course):

User.ts

@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>;
}

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>;
}

I can access the class reference from the User side just fine, but I cannot access the classmaster (user reference) from the Class side. I tried populating as well, but no luck. How can I access the user from the inverse side? Is this not possible? Here's an example code:

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

Solution

  • This is unfortunately not possible via populate hints. In SQL drivers this exact case is solved via joining the owning side automatically, to know the FK, but as mongo has no joins, we cant really do that. Although it would be nice experiment to do it via $lookup.

    What you can do instead is to query the owning entity directly, and assign it to the relation property. Something like this:

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