NestJS/Mongoose - Create an Array of Object with reference to another Schema

Viewed 8705

I'm building the back-end side of a personal application, and I have two particular models/schemas. One if for Products an another for Orders. I want to do the following:

The Orders need to have the following array with this structure:

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

The product should be an ObjectId of mongo, and this needs a reference for a 'Product' model.

How I can reach this? I don't really know how to "type" this with the @Prop() decorator.

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

This is my Order Schema:

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

The best way to achieve both reference population and mongoose schema validation is to create a subschema for the nested entity.

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 {
   // ...

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