Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

388
Views
Create table without creating new collection in MongoDB, NestJs

I struggle with the problem. In my app, I have to create an order with several attributes and one of them is an array of ordered products. In the orderedProduct array, each object should have productId and the amount.

But, I don't want to create a new collection called OrderedProduct. In the current solution, it is creating both: empty orderedproduct and orders. And I have 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 not been able to do this. I will be appreciated for your help!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I think you need to use the schema of your sub object. something like:

@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]
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!