NodeJS NestJS/Mongoose -引用另一个模式创建对象数组

yhuiod9q  于 2022-12-18  发布在  Node.js
关注(0)|答案(2)|浏览(179)

我正在构建一个个人应用程序的后端,我有两个特定的模型/模式。一个用于产品,另一个用于订单。
Orders需要具有以下结构的数组:

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);

eqqqjvef

eqqqjvef1#

@Prop({
    type:[{quantity:{type:Number}, product:{type:Schema.Types.ObjectId}}]
  })
  products: { quantity: number; product: Product }[];
hivapdat

hivapdat2#

实现引用填充和mongoose模式验证的最佳方法是为嵌套实体创建一个子模式。

import { Document, SchemaTypes, Types } from 'mongoose';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

@Schema({ _id: false, versionKey: false })
class OrderProduct {
  @Prop({ required: true })
  quantity: number;

  @Prop({ type: [SchemaTypes.ObjectId], ref: 'Product', required: true })
  product: Product[];
}

const OrderProductSchema = SchemaFactory.createForClass(OrderProduct);

@Schema()
export class Order {
   // other order schema props ...

  @Prop([{ type: OrderProductSchema }])
  products: OrderProduct[];
}

相关问题