MongoDB $graphLookup omits repeat records

58 Views Asked by At

I have collection in which I have defined all my products and their sub-products. The sub-products are not defined as sub-documents but as a separate document in the collection.

const productTypeSchema = mongoose.Schema({
 name: { type: String, required: true },
category: { type: String, required: true },
  subProducts: [subProductsSchema],
})

const subProductsSchema = mongoose.Schema({
  name: { type: String, required: true },
  subProductId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "product",
  },
});

A sample record be like

{ _id: 1, name: 'Steel Grid', Category: 'Finished Product',
     subProducts: [{ _id: 6, name: 'Load Bar', subProductId: 2},
                   { _id: 7, name: 'Cross Bar', subProductId: 2}]
},
{ _id: 2, name 'Steel Bar', Category: 'Raw Material'}

To fetch a product and all its sub-products, I use the @graphLookup

        $graphLookup: {
          from: "product",
          startWith: "$_id",
          connectFromField: "subProducts.subProductId",
          connectToField: "_id", 
          depthField: "subpartlevel",
          as: "subParts",
        },

My issue is that the $graphLookup fetches only one subproduct as both of them are pointing to a single document in the collection. Is there a way to fetch both records?

Experts please help. Thank you.

0

There are 0 best solutions below