Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda