Proper way to link another class in typegoose (mongoose) and store only the reference (ObjectId)?

When attempting to save certain fields in ObjectId only in the mongo db, I encountered an issue with the code below:

@ObjectType()
export class User {
  @prop()
  @Field()
  name: string;

  @prop({ ref: () => OtherClassA })
  @Field()
  otherClassA: OtherClassA;

  @prop()
  @Field()
  otherClassB: OtherClassB;
}

@ObjectType()
export class OtherClassB {

  @prop()
  @Field()
  name: string;

  @prop({ ref: () => OtherClassB1 })
  @Field()
  otherClassB1: OtherClassB1;

  @prop({ ref: () => OtherClassB2 })
  @Field()
  otherClassB2: OtherClassB2;
}

After saving the data, it appeared as shown below in the mongo db:

user {
  _id
  name
  otherClassA: ObjectId("607910cdf9961b0dcf50b5d8")
  otherClassB {
    otherClassB1 {
      // the whole object of otherClassB1
    }
    otherClassB2 {
      // the whole object of otherClassB2
    }
  }
}

This result was not expected....

The desired outcome was:

user {
  _id
  name
  otherClassA: ObjectId("607910cdf9961b0dcf50b5d8")
  otherClassB {
    otherClassB1: ObjectId("607910cdf1231b0dcf51a456")
    otherClassB2: ObjectId("607910cdf1231b0dcf51a5bf")
  }
}

How can I ensure that only references are saved in this structure using typegoose(mongoose)?

2021-4-26 Updated:

typegoose v7.6.0

mongoose v5.10.18

typescript v4.0.5

mongodb v3.6.6

Answer №1

My suggested code implementation below includes the use of the Ref:

import { prop, Ref} from '@typegoose/typegoose';

export class User {

  // ...

  @prop({ ref: () => OtherClassB1 })
  otherClassB1: Ref<OtherClassB1>;
}

Link to documentation:

On a side note, I am not familiar with the @Field() syntax and do not believe it is a feature of Typegoose.

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

Enhanced functionality for Thingworx using ThreeJS

I'm currently facing an issue while developing a 3 JS extension for Thingworx, specifically with the renderHtml function when working with a 3 JS canvas (Check out the code). //runtime.ts file renderHtml(): string { let htmlString = '<div ...

Having trouble establishing a connection to the database with mongoDB and mongoose

My first experience with using mongoDB has been a challenging one. Despite creating a cluster on Atlas, I am encountering errors while trying to connect. keys.jss module.exports = { mongoURI: 'mongodb+srv://john:<********>@mern-shopping-i5 ...

"Mongo CSFLE data encryption keys can be fetched either once or in batches, depending on

Exploring how MongoDB client-side fields level encryption works when dealing with multiple data encryption keys stored in a key vault. If we fetch X records with 1 field encrypted using Y distinct data encryption keys, I'm curious about the driver&apo ...

I am currently working on personalizing the error structure for a Rest API using Spring Boot

The code below shows the syntax, which is causing a compilation error in Java: cannot infer type arguments for org.springframework.http.ResponseEntity<> Could anyone please suggest how to resolve this error? @ExceptionHandler(ValidationException.cl ...

What is the best practice for storing API key references and env files within a Node.js application?

What is the proper way to handle sensitive information like api keys and mongo URL in my app.js file? Should I create a separate configuration file, such as config.js, export it as a module, then require it in my app.js file? How can I ensure that when t ...

Using Html to differentiate input based on type

Looking for input on the code snippet below: <table class="details-table" *ngIf="animal && animaldata"> <tr *ngFor="let attribute of animaldata.Attributes"> <td class="details-property">{{ attribute.AttributeLabel }}& ...

What could be causing the issue with Virtual Populate not functioning on Node.js and Mongoose? Here's the scenario: User provides

When a user gives a review on a specific product ID, it is stored in the review model database instead of the product model database. Virtual populate is used in the product model to display the user review in JSON format without saving it in the database. ...

Function that yields promise result

I need help figuring out how to make this recursive function return a promise value. I've attempted various approaches, but they all resulted in the search variable ending up as undefined. public search(message: Message) { let searchResult: strin ...

The field 'user' is not recognized on the object type WritableDraft

I've set up a redux userSlice to retrieve user data from the store. client/src/redux/features/userSlice.ts import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"; import { User } from "../../interfaces/user&quo ...

CDK Error: Unable to locate MethodResponse in AWS API Gateway configuration

I'm facing an issue in vscode while trying to access the MethodResponse interface from apigateway. Unfortunately, I'm getting an error message: The type 'typeof import(".../node_modules/aws-cdk-lib/aws-apigateway/index")' d ...

UnresolvedPromiseRejectionNotice: MongoDBServerSelectionError: The connection to the 'ip-address' monitor has been terminated. Surprisingly, the code ran smoothly on my colleague's computer

Completely new to this world (less than a month new), my tech lead shared a GitHub repo of an API that I cloned onto my local machine. Following the instructions, I used npm run start in the terminal and received this output: C:\Users\my_path > ...

When using Ionic 3 on an Android device, the keyboard is causing the tabs and app content to shift upwards

I'm currently working on an Ionic 3 app and encountering a problem. Whenever I click on the search function, the keyboard opens and pushes all the content of the app to the top. https://i.sstatic.net/GaPW8.png https://i.sstatic.net/7d6Fm.png Here i ...

Incorporate a fresh feature into a current file

Is there a way to add an attribute to all documents in a collection using mongoengine? I've experimented with a few methods: for d in MyDocuments.objects: d.attr = 'test' d.save() Although this code runs without errors, it doesn&ap ...

"What is the process for querying data from multiple collections in mongodb through aggregate?

I have a MongoDB setup with two collections as follows: PRODUCTS: [ { "_id": "5ebb0984e95e3e9e35aab3bf", "name": "Product 1", "brand": "ABC", "code": "7891910000190", "description": "Lorem Ipsum" }, { ...

The issue lies with Mongoose's inability to convert a string into an object key

When making an ajax call, I pass the object below to Mongoose: {category: 'name', direction: 1} To sort the query results using Mongoose, I use the following code: Site.find(query).sort(sortBy) Prior to this call, I need to format the object ...

Learning Angular2: What is the mechanism behind the automatic incrementation of the ID variable in this particular section?

In This specific part of the Angular2 Tutorial there is a feature that allows users to add new items to an array. Somehow, when the item is added, the ID is automatically incremented but the exact process behind this automation remains a mystery. I am awa ...

How do I go about utilizing or bringing in those constants within the Drawerr.js module?

Currently, working with Next.js, I have defined some constants in the Nav.js file: export default function NestedList() { const [value,setValue]=React.useState(); const theme=useTheme(); const isMatch=useMediaQuery(theme.breakpoints.down('lg&apo ...

Retrieve object from nested array based on its id using Angular 6

I have an array of courses, where each course contains an array of segments. In my course-detail component, I have a specific course and I want to retrieve a segment by its ID. For example, let's say I have the following course: { "id": 1, ...

Oops! A mistake was made by passing an incorrect argument to a color function. Make sure to provide a string representation of a color as the argument next time

Encountering an issue with a button react component utilizing the opacify function from the Polished Library The styling is done using styled-components along with a theme passed through ThemeProvider. Upon testing the code, an error is thrown. Also, the ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...