Search code examples
node.jstypescriptmongoosenestjs

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


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

Solution

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