【问题标题】:NestJS/Mongoose - Create an Array of Object with reference to another SchemaNestJS/Mongoose - 参考另一个模式创建一个对象数组
【发布时间】:2021-06-21 12:19:10
【问题描述】:

我正在构建个人应用程序的后端,并且我有两个特定的模型/架构。一个用于产品,另一个用于订单。我想做以下事情:

订单需要具有以下具有此结构的数组:

products: [
  {
    product: string;
    quantity: number;
  }
]

产品应该是 mongo 的 ObjectId,这需要一个“产品”模型的参考。

我怎样才能做到这一点?我真的不知道如何用 @Prop() 装饰器“输入”这个。

@Prop({
    // HOW I DO THIS?
})
products: [{ quantity: number; product: mongoose.Types.ObjectId }];

这是我的订单架构:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Document } from 'mongoose';

export type OrderDocument = Order & Document;

@Schema()
export class Order {
  @Prop({ type: String, required: true })
  name: string;

  @Prop({ type: Number, min: 0, required: true })
  total: number;

  @Prop({
    type: String,
    default: 'PENDING',
    enum: ['PENDING', 'IN PROGRESS', 'COMPLETED'],
  })
  status: string;

  @Prop({
    // HOW I DO THIS?
  })
  products: [{ quantity: number; product: mongoose.Types.ObjectId }];

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Customer',
    required: true,
  })
  customer: mongoose.Types.ObjectId;

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  })
  owner: mongoose.Types.ObjectId;

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

export const OrderSchema = SchemaFactory.createForClass(Order);

【问题讨论】:

  • 也许你应该使用mysql或者其他关系型数据库,因为如果表很多,你会更容易组织关系

标签: node.js typescript mongoose nestjs


【解决方案1】:
@Prop({
    type:[{quantity:{type:Number}, product:{type:Schema.Types.ObjectId}}]
  })
  products: { quantity: number; product: Product }[];

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 2021-03-30
    • 2020-10-02
    • 2017-06-17
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多