NestJS/Mongoose-创建一个引用另一个Schema的对象数组



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

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

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

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

我怎么能做到这一点?我真的不知道如何";类型";这与CCD_ 2装饰器有关。

@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);
@Prop({
type:[{quantity:{type:Number}, product:{type:Schema.Types.ObjectId}}]
})
products: { quantity: number; product: Product }[];

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

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[];
}

相关内容

最新更新