I try to populate products data in order. I use mongoose with nestjs and graphql. The problem is that I don’t want to create new collection. So all I want to do is to create an order which has attribute orderedProductArray
. This consists of product
and amount
. Product has a reference to Product
object.
Schemas
@Schema()
export class OrderedProduct {
@Prop(() => ID)
_id: string
@Prop(() => Int)
amount: string
@Prop({ type: Types.ObjectId, ref: Cloth.name })
product: Cloth
}
export const OrderedProductSchema = SchemaFactory.createForClass(OrderedProduct)
@Schema()
export class Order {
@Prop()
_id: string
@Prop({ type: Date, default: Date.now })
confirmedDate: Date
@Prop({ type: Types.ObjectId, ref: OrderStatus.name })
orderStatus: OrderStatus
@Prop()
userName: string
@Prop()
email: string
@Prop()
phoneNumber: string
@Prop({ type: [OrderedProductSchema] })
orderedProductArray: [OrderedProduct]
}
export const OrderSchema = SchemaFactory.createForClass(Order)
And the service:
async getOrderById(getByIdArgs: GetOrderByIdArgs): Promise<Order> {
try {
const searchedOrderId = await this.orderModel
.findById(getByIdArgs)
.populate({
path: 'orderedProductArray',
populate: {
path: 'product._id',
model: 'Cloth'
}
})
.exec()
if (searchedOrderId) {
return searchedOrderId
}
throw new NotFoundException('The given id does not exist')
} catch (error) {
throw new NotFoundException(error)
}
I will be appreciated for your help. I tried almost everything that I’ve found in StackOverflow. Thanks in advance!!!