Tips for effectively managing and storing data from a modal in Angular 12 beyond just the ID

I will provide an example to clarify my question as I am struggling to find a better way to phrase it.

Here are the interfaces I am working with :

import { Product } from "./product.model";
import { User } from "./user.model";

export interface Order{
  _id?: string;
  user: User;
  product: Product;
  quantity: number;
  price: number;
}


export interface Product {
  _id: string;
  title: string;
  price: number;
  images: string;
  stock: number;
  description: string;
  category: string;
  createdAt:Date
}

export interface User {
  _id:string,
  username:string,
  email:string,
  role:string,
  password:string,
  token:string
}

In the checkout component, there is a function for creating and storing orders :

createOrder(): void{
  this.cart.forEach((item)=>{
    this.order = {
      user: this.user,
      product: item.product, 
      price: item.product.price * item.number,
      quantity: item.number
    }

    this.orderService.post(this.order).subscribe(
      (res:Order) => {
        console.log('Order created');
      },
      (err)=>{
        console.log(err);
      })
  })
}

The data is being successfully added but only the PRODUCT ID and the USER ID are stored, not all the data associated with them.

I would like the output to be structured like this:

{
  _id:1,
  user: {
    _id:2,
    username:'someone'
  },
  product: {
   _id: 1,
   name:'something',
   price: 99.99,
   stock: 244,
  },
  price: 201.00,
  quantity:2
}

However, currently, it looks like this:

 {
    _id:1,
    user:2,
    product:1,
    price: 201.00,
    quantity:2
 }

Any assistance on achieving the desired structure would be greatly appreciated.

Answer №1

Within the realm of mongoDB, there exists a powerful tool known as the populate operator. This operator takes in the unique identifiers (such as user_id, product_id, order_id) and retrieves all or specific parts of the related data (user, product, order) based on their respective models within the backend system. The outcome is contingent upon the parameters selected.

For instance, when retrieving a list of orders, utilizing the populate operator will fetch detailed information about users in the form of an object containing all relevant user data. The same applies to products.

It is advisable to collaborate with your backend team as different backend technologies offer their own versions of the populate() operator or its equivalents.

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

Exploring Angular's Observables for handling HTTP requests

Exploring Angular Observable Documentation As I delved into the Angular observable documentation mentioned above, I came across a section that compares promises with observables. Observables provide many values, while promises provide one. This characte ...

Issue with auto formatting quotes in IntelliJ / WebStorm is no longer functioning as expected

Currently, my TSLint configuration is set to permit the use of single quotes (') instead of double ones ("). Previously, I was able to conveniently switch all instances of " to ' in a file by using the Reformat Code shortcut CTRL + ALT ...

Developing an NPM package within a yarn workspace monorepo featuring internal dependencies

Currently, I am working on a project where I am utilizing yarn workspace to develop a library that will eventually be published on NPM. This library has a dependency on a private core package within the same workspace. As per my understanding, the workspac ...

Encountering an issue with testing CKEditor in Jest

Testing my project configured with vite (Typescript) and using jest showed an error related to ckeditor. The error is displayed as follows: [![enter image description here][1]][1] The contents of package.json: { "name": "test-project" ...

Angular 6 Checkbox Selector - Filtering Made Easy

How can I filter a list of JSON objects (Products) by the 'category' variable using checkboxes? An example product object is shown below: { 'bikeId': 6, 'bikeName': 'Kids blue bike', 'bikeCode': ...

"Typescript throws a mysterious 'Undefined value' error post-assignment

I'm currently working on a task to fetch my customer's branding information based on their Id using Angular. First, I retrieve all the customer data: this.subscription = this.burstService.getBurst().subscribe(async(response) => { if (r ...

Setting up admin credentials with TypeScript in Firebase cloud functions

While working with Firebase cloud functions in JavaScript, I utilized the following code snippet to initialize admin: admin.initializeApp({ credential: admin.credential.cert(require('./key/firebase-adminsdk.json')), databaseURL: "https://app ...

Retrieve the time zone setting from either my browser or server, and then incorporate it into angular2-highcharts

My current timezone setup is done manually using the timezoneOffset function from the Highcharts API. I am currently in GMT+2 so I set it to -2 * 60. However, I encountered an issue where my setup would not work properly when the hour changes in October. T ...

Attempting to perform an API invocation on a distant endpoint utilizing NestJS

var unirest = require("unirest"); var req = unirest("GET", "https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data"); req.query({ "ingr": "1 large apple" }); req.headers({ &qu ...

An error occurred while running React, Next.js, and Type Script: Unhandled Runtime Error - TypeError: Unable to access 'value' property of undefined

I have been working on a multi-page form and using the antd package to add some styling to it. On the main page of the form, I implemented the following code (making sure I imported everything required). export class CreateNewContract extends Component ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

How to disable typescript eslint notifications in the terminal for .js and .jsx files within a create-react-app project using VS Code

I'm currently in the process of transitioning from JavaScript to TypeScript within my create-react-app project. I am facing an issue where new ESLint TypeScript warnings are being flagged for my old .js and .jsx files, which is something I want to avo ...

Angular 2's @ViewChild directive may sometimes yield undefined results

After consulting various related posts and documentation, I am still struggling to achieve the desired outcome with @ViewChild. My main objective is to adjust the scroll position of a div. This particular element is not a component, but a regular div in m ...

The pagination, sorting, and filtering features in my Angular Material project seem to be malfunctioning

Having created a project on Angular CLI 7, I decided to incorporate Angular Material into it. Despite adding modules for table pagination, expansion, filter, and sort in the app modules file, I am facing difficulties making the paginator, sorting, and fil ...

Is data binding not functioning properly in Angular 8?

This query has been raised multiple times in the past and I have reviewed all the suggested solutions. However, I am encountering a common issue - how to retrieve data from the parent component to the child component. I'm unsure of where I'm goin ...

Modifying PDF files using Angular 4

Encountering a CORS problem in node v8.9.4. Error message - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200& ...

Reset Ng autocomplete once an option has been chosen

My current challenge involves the desired behavior in which, when an option is selected from an autocomplete input, it should add an element to the data array (which it does successfully), and then clear the autocomplete input for selecting another option ...

An easy guide on utilizing ngSwitch for datatype selection in Angular

While working in angular2, I came across a question regarding the usage of ngSwitch to load <div> tag based on the datatype of a variable. Is it possible to achieve something like this: <div [ng-switch]="value"> <p *ng-switch-when="isObj ...

Change the property value prior to running TypeScript validation

I possess the following object: const translations = { msg_hello: 'Hello', msg_bye: 'Bye' } In addition, I have a function that is structured as such: const generateTranslation = (partialKey: string): keyof typeof translations ...

TypeScript and Node.js: The type of 'this' is implicitly set to 'any'

Help Needed with TypeScript issue: An issue is arising in my TypeScript code related to a mongoose schema's post function. It is used to generate a profile for a user upon signing up, using the User model. Even though the code functions properly, th ...