Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

320
Views
Mongoose/MongoDb find documents with reverse reference in an array

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 ?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!