Having trouble retrieving information from the opposite side of a one-to-one relationship

Here are two simplified entities that I am working with:

User.ts

@Entity({ collection: "users" })
export class User {
    @PrimaryKey()
    _id!: ObjectId;

    @SerializedPrimaryKey()
    id!: string;

    /** The user's lead class */
    @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 no assigned classmaster.
     */
    @OneToOne({ mappedBy: "lead_class" })
    classmaster?: Reference<User>;
}

Although I can access the class reference from the User side, I'm having trouble accessing the classmaster (user reference) from the Class side. Even after trying to populate, I have been unsuccessful. How can I retrieve the user from the inverse side? Is this not achievable? Below is a code snippet for reference:

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

Answer №1

Unfortunately, using populate hints does not allow for this functionality. SQL drivers have the capability to automatically join the owning side in cases like these to determine the foreign key. However, since MongoDB does not support joins, we are unable to replicate this behavior. It might be interesting to see what happens if we try utilizing $lookup.

Instead of using populate hints, a workaround is to directly query the owning entity and assign it to the relation property. Here is an example:

let x = await db.xs.findOneOrFail("example_id");
x.property = await db.properties.findOne({ x: x.id });
console.log("Property details: ", x.property);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uploading multiple files to MongoDB with Multer and Node.js

I am struggling to upload multiple files to MongoDB using Node and multer. I attempted to handle it with the code below, but it seems unsuccessful. While uploadImg.array() is creating files locally, I am unable to create new uploads in MongoDB. router.post ...

Adding additional values to an existing array within a MongoDB collection using Java

My mongo collection looks like this: { "_id": ObjectId("55cad746aed75601b4822cc9"), "entityId": "12", "entityType": "a", "nameIdentity": [{ "fName": "abc", "lName": "def", "dob": "00", "address": "xyz" } ...

Exploring Deeply Nested Data Structures in Angular

I'm having trouble searching for the first name, middle name, and last name together. Currently, I can only search for each separately. For example: When I try to search for "Jacob jj9eqwif Nguyen", it doesn't work. But if I search for Jacob, it ...

What is the best way to organize my node.js, express, and mongodb application?

I've been thinking about how different developers organize their Node.js apps. My usual approach involves creating models, views, and controllers. But since I'm new to the Node.js world, I'm eager to understand more about the community&apos ...

Updating and inserting data with Mongoose's upsert feature

Encountering an issue when attempting to execute a findOneAndUpdate operation: MongoError: E11000 duplicate key error collection: AdStitchr.listeners index: uuid dup key: { UUID: "4502191d-1975-463d-8fc1-8ab3537cc9c8" } at Connection.<anonymous ...

Having trouble resolving rxjs/operators when using ngx-datatable?

I am attempting to integrate ngx-datatable into my Angular-2 project. I have followed all the steps outlined here, but I encountered the following error: ERROR in ./~/@swimlane/ngx-datatable/release/index.js Module not found: Error: Can't re ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

Achieve the retrieval of both categories and sub-categories in one consolidated API response

I have a main collection named Categories which contains another collection called Subcategories. The Categories collection includes an array of subcategory IDs from the Subcategories collection. Here is the structure of my documents: Categories collectio ...

Comparing Angular 6 Subjects and BehaviorSubject

Recently, I developed an application where I utilized the behavior subject for data transfer between all components. I am curious to know if this is considered a best practice when working with observables. import { BehaviorSubject } from 'rxjs' ...

Searching an object using multiple criteria(inputs)

I'm dealing with numerous inputs that my object needs to filter through. While I can hardcode it, I believe there must be a more efficient approach. Filter state : const [filters, setFilters] = useState<FiltersType>({ login: "", ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

Create a new schema using the Mongoose `.create` method

My challenge is with the userInfo.create function in my game development project. When a user logs in, a get request is sent to fetch their profile info. If it doesn't exist, I need to create it. The process involves two steps: first is creating basic ...

Updating a specific subfield of a document in Mongoose using NodeJS with Express

I have set up the following schemas in my Node server SCHEMAS const mongoose = require('mongoose'); const Schema = mongoose.Schema; const dataSchema = new Schema({ time: Date, value: String }); const nodeSchema = new Schema({ name: ...

What is the best way to display mongoose/mongodb queries containing date fields in a customized string format?

When querying mongoDB through mongoose, I encountered an issue with fields of Date type. The result of the query is being passed to express as a web response, but somewhere along the way, the Date is getting converted to a string like "2016-09-28T03:19:51. ...

The fusion of graphene-mongo with intricate nested json structures

I have two documents stored in a MongoDB database: >db.user.find(); { "_id" : ObjectId("623d12f5ee5204c41f028944"), "uid" : "you", "uid_number" : 5678, "eppns" : [ "<a href="/cdn-cgi/l/ ...

What steps should be followed in order to generate a child or item with no assigned key

Here is my TypeScript code designed to automatically record the time of data creation: import * as functions from 'firebase-functions'; export const onAccCreate = functions.database .ref('/Agent/{AgentID}') .onCreate((snapshot, contex ...

What is the method for reaching a static member of a class within a decorator for a method of the same class?

Upon the release of TypeScript 5.0, the new decorator APIs have been introduced and I am eager to utilize them for automatically providing parameters to a method from a static property within the same class. The decorator parameters and factory are defined ...

What are the steps to incorporate SignalR into a TypeScript project?

Working on an asp.net mvc 4.5 project with typescript in the client side, I successfully installed and configured signalR on the server side. To integrate it into my project, I also installed signalr.TypeScript.DefinitelyTyped with jquery. In my typescrip ...

Leverage the #each method with an argument in Meteor to iterate

As a beginner with the Meteor framework, I am currently working on displaying data using meteor + mongo + spacebars. However, I encountered an issue where I need to use an argument with the spacebar #each, and it doesn't seem to allow it. Here is my ...

Unable to transfer token to a different file within cypress

I'm encountering an issue where I make an API request to get a token and try to use it in another function located in a separate file. However, when I export the token from one file to another, it does not work as expected. The 'activate user&apo ...