【问题标题】:Create table without creating new collection in MongoDB, NestJs在 MongoDB、NestJs 中创建表而不创建新集合
【发布时间】:2022-01-13 21:50:55
【问题描述】:

我正在努力解决这个问题。在我的应用程序中,我必须创建一个具有多个属性的订单,其中一个是一系列已订购的产品。在orderedProduct数组中,每个对象都应该有productId和数量。

但是,我不想创建一个名为 OrderedProduct 的新集合。在当前的解决方案中,它同时创建:空的有序产品和订单。我有一个问题

"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\""

架构

@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
}

我无法做到这一点。我将不胜感激您的帮助!

【问题讨论】:

    标签: javascript typescript mongodb nestjs


    【解决方案1】:

    我认为您需要使用子对象的架构。类似:

    @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]
    }
    

    【讨论】:

    • 谢谢!但是由于某种原因,在数据库中,添加了金额,但没有任何产品。
    • 我找到了原因,我的输入道具名称不同。但除此之外,谢谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多