Generate a table in MongoDB using NestJs without the need to create a new collection

I am facing a challenge with my app where I need to create an order with multiple attributes, one of which is an array of ordered products. Each object in the orderedProduct array must include the productId and the amount.

However, I do not want to create a new collection named OrderedProduct. The current solution is creating both an empty orderedproduct and orders, resulting in an issue:

"Cast to ObjectId failed for value \"{\n  productId: { _id: '0a8b51d0-5bb1-4ab6-83d0-5b0c15f44e2b' },\n  amount: 3\n}\" (type Object) at path \"_id\" for model \"OrderedProduct\""

Schemas

@Schema()
export class Order {
  @Prop()
  _id: string

  @Prop({ type: Date, default: Date.now })
  confirmedDate: Date

  @Prop({ type: Types.ObjectId, ref: OrderStatus.name })
  orderStatus: OrderStatus

  @Prop()
  userName: string

  @Prop()
  email: string

  @Prop()
  phoneNumber: string

  @Prop({ type: Types.ObjectId, ref: OrderedProduct.name })
  orderedProductArray: [OrderedProduct]
}

@Schema()
export class OrderedProduct {
  @Prop(() => Int)
  amount: string

  @Prop({ type: Types.ObjectId, ref: Cloth.name })
  product: Cloth
}

I have been unable to resolve this issue on my own. Any assistance would be greatly appreciated!

Answer №1

To properly structure your sub object, consider utilizing the schema like so:

@Schema()
export class OrderedProduct {
  @Prop(() => Int)
  amount: string

  @Prop({ type: Types.ObjectId, ref: Cloth.name })
  product: Cloth
}
export const OrderedProductSchema = SchemaFactory.createForClass(OrderedProduct);


@Schema()
export class Order {
  @Prop()
  _id: string

  @Prop({ type: Date, default: Date.now })
  confirmedDate: Date

  @Prop({ type: Types.ObjectId, ref: OrderStatus.name })
  orderStatus: OrderStatus

  @Prop()
  userName: string

  @Prop()
  email: string

  @Prop()
  phoneNumber: string

  @Prop({ type: [OrderedProductSchema] })
  orderedProductArray: [OrderedProduct]
}

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

React.js: You cannot call this expression. The type 'never' does not have any call signatures

Could someone help me troubleshoot the error I'm encountering with useStyles? It seems to be related to Typescript. Here's the line causing the issue: const classes = useStyles(); import React from "react"; import { makeStyles } from & ...

Connection between mapStateToProps and mapActionsToProps failing to trigger in react component

I am facing an issue with my component (SearchFilter.js) where the connect method is not triggering mapStateToProps and mapActionsToProps on export. The problem is that mapStateToProps is not firing at all -- no props (neither state nor actions) are showi ...

Locate and filter elements by using the react-testing-library's getAll method

On my page, I have a collection of unique checkbox elements that are custom-designed. Each individual checkbox has the following structure: <div className="checkbox" role="checkbox" onClick={onClick} onKeyPress={onKeyPress} aria-checked={getS ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

Automatically generated error notifications for Express-Validator

I am looking to implement an Express API and incorporate request input validation using express-validator. Here is my current validation middleware: protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> ...

Angular ng-repeat encounters difficulty in parsing Arabic object

As I create a JSON object that contains Arabic content shown below $scope.arabicContent = ["ردهة","قاعة الاجتماعات","مبرمجين الجوال","المدراء","المحاسبة","المحاسبة","المبرمجين‎","مطبخ‎ ...

Gain access to TypeScript headers by typing the request (req) object

Is there a way to access headers in a method that is typed with Express.Request? Here's an example code snippet: private _onTokenReceived(req: Express.Request, res: Express.Response): void { const header: string = req.headers.authorizatio ...

What is the best way to retrieve an object from a loop only once the data is fully prepared?

Hey, I'm just stepping into the world of async functions and I could use some help. My goal is to return an object called name_dates, but unfortunately when I check the console it's empty. Can you take a look at my code? Here's what I have ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Error: Attempting to access the 'email' property of an undefined variable is not allowed

router.post('/login', async (res, req) => { const{error} = loginValidation(req.body); if (error) return res.status(400).send(error.details[0].message); //user validation const user = await User.findOne({ email: req.body.em ...

What issues can trailing white space cause in TypeScript coding?

While I understand that linting is the reason for this, why are trailing spaces considered problematic? I plan to disable this feature in tslint.json, but before I make that change, I want to ensure I'm not making a mistake. Visual Studio Code alert ...

Tips for executing an npm command within a C# class library

I am currently developing a project in a class library. The main objective of this project is to execute a JavaScript project using an npm command through a method call in C#. The npm command to run the JavaScript project is: npm start The JavaScript ...

During the transpiling process, the metadata of an Angular component may become lost

Encountering another error: Uncaught Error: Unexpected value 'UserDialogComponent' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Current behavior Summary: When incorporating an external libra ...

Nested views within nested views in UI Router

Exploring the capabilities of angular-ui and specifically experimenting with the ui-router module to create nested views. I'm running into an issue where a partial isn't rendering within another partial: The structure of nesting looks like this: ...

Optimizing Angular.js templates for faster loading using Node.js pre-compilation

As I delve into learning Angular and integrating it with my current Node.js framework, I find myself facing some challenges. Previously, I utilized Handlebars.js as my templating engine in Node.js, where I would build the context on the server side and the ...

Exploring the power of jQuery.grep for locating specific keywords and phrases

Struggling to figure out how to extract keywords and phrases from a textarea by using jQuery.grep in a way that does not require an exact match but rather checks if it contains specific keyword(s) and/or phrase(s) in an array. Currently, the code provided ...

Properly transform a set of conditions from If statements to R.cond

I have a series of If statements that I need to convert to Ramda's conditional function. However, when I try to do so, I encounter an error saying that "Never is not assigned to Element." It seems like I am making a mistake somewhere: if (cond1) ret ...

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

Updating a React JS State using a Parameter

Is it feasible to develop a function that accepts a parameter (either a string of the state name or the actual state) and then assigns the state related to the parameter? SetState(x) { // Suppose x can be any state we have already defined (it sh ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...