I have 2 schemas:
Order
- orderId
- date
- items: OrderItem[] (Array of ObjectIds of OrderItem)
OrderItem
- name
- price
- discount
Now I have the list of order items and I want to associate them with order.
As I'm storing the references in the Order.
But I need to list all the OrderItems in a separate page from where I can link the items to order via API. So I need to see which items are already linked to an order and which are still pending. Is there any way to get the OrderId in the list of OrderItem with the use of mongoose?
I've tried to reverser reference as well in the OrderItem by including the orderId in the OrderItem schema. But, it causes an issue when I try to link the order items which are already linked.
Say for example, I've 2 orders:
o1:
items: i1, i2
o2:
items: i3, i4, i5
i1:
orderId: o1
i2:
orderId: o1
i3:
orderId: o2
i4:
orderId: o2
i5:
orderId: o2
i6:
orderId: o2
So from the list of items, user selects i2, i3 to link to o3. Then the following updates has to be made:
o3 -> items: i2, i3
i2 -> orderId: o3
i3 -> orderId: o3
But it leaves a situation where o1 still holds i2 and o2 still holds i3. Those documents also needs to be updated. These many operations leaves an issue for simple linking leads to an complex ambiguous situation.
If there's a way I can get list of items and orderId it belongs to without storing orderId in the OrderItem and only storing it in the Order.items can solve this situation.
Is there any way I can achieve this with mongoose / mongodb ?
Storing orderItem without orderId lead you to the problems when retrieve order detail from orderItem. Storing orderItemId in order collection is not useful as you think. Because you can get them from orderItem collection. Query nested data is not easy. Try to bring all of them into a line. Just my opinion.
Order
- salerId
- buyerId
- date
OrderItem
- orderId
- name
- price
- discount