Skip to content

Instantly share code, notes, and snippets.

@Rafik-Belkadi-malou
Last active September 28, 2022 09:32
Show Gist options
  • Save Rafik-Belkadi-malou/c25e276b3068ad0a43790a9296bd2991 to your computer and use it in GitHub Desktop.
Save Rafik-Belkadi-malou/c25e276b3068ad0a43790a9296bd2991 to your computer and use it in GitHub Desktop.
import { Schema, model } from 'mongoose'
import { IProduct } from './product'
// Utility type which you can put in your utils file
type ID = Schema.Types.ObjectId
export interface IOrder {
_id?: ID
// Represents the relation between the order and the product
productsIds: ID[]
quantity: number
// Optional type used when we want to populate the product in the order, will be defined as a virtual on the schema
products?: IProduct[]
}
const orderSchema = new Schema<IOrder>({
productsIds: [{ type: Schema.Types.ObjectId, ref: 'Product' }],
quantity: Number
})
// Define the product field as a virtual for when we populate it for better usage
orderSchema.virtual('products', {
ref: 'Product',
localField: 'productID',
foreignField: '_id',
})
export const Order = model<Iorder>('Order', orderSchema)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment