Last active
September 28, 2022 09:32
-
-
Save Rafik-Belkadi-malou/c25e276b3068ad0a43790a9296bd2991 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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