[英]Mongoose/MongoDb find documents with reverse reference in an array
I have 2 schemas:我有 2 个模式:
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
.因为我将引用存储在Order
中。
But I need to list all the OrderItems
in a separate page from where I can link the items to order via API.但是我需要在一个单独的页面中列出所有OrderItems
,我可以通过 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?有什么方法可以使用 mongoose 获取OrderItem
列表中的OrderId
?
I've tried to reverser reference as well in the OrderItem
by including the orderId
in the OrderItem
schema.我还尝试通过在OrderItem
架构中包含orderId
来反向引用OrderItem
。 But, it causes an issue when I try to link the order items which are already linked.但是,当我尝试链接已经链接的订单项目时,它会导致问题。
Say for example, I've 2 orders:例如,我有 2 个订单:
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.因此,从项目列表中,用户选择 i2、i3 以链接到 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
.但它留下了o1
仍然持有i2
并且o2
仍然持有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.如果有一种方法可以获取项目列表和它所属的orderId
,而无需将orderId
存储在OrderItem
中,而仅将其存储在Order.items
中可以解决这种情况。
Is there any way I can achieve this with mongoose / mongodb?有什么方法可以用 mongoose / mongodb 来实现吗?
Storing orderItem without orderId lead you to the problems when retrieve order detail from orderItem.当从 orderItem 检索订单详细信息时,存储没有 orderId 的 orderItem 会导致您遇到问题。 Storing orderItemId in order collection is not useful as you think.如您所想,将 orderItemId 存储在订单集合中并没有用。 Because you can get them from orderItem collection.因为您可以从 orderItem 集合中获取它们。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.