Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
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);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

@Prop({
    type:[{quantity:{type:Number}, product:{type:Schema.Types.ObjectId}}]
  })
  products: { quantity: number; product: Product }[];
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!