0

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.

Mahesh
  • 1
  • 3
  • Do you want `$lookup` instead? Or can sub-products themselves contain sub-products? – user20042973 Oct 06 '22 at 12:26
  • It's a multiple level table where the sub-products will have their own sub-products. A recursive way (like $graphLookup) will make my work easy and elegant. – Mahesh Oct 07 '22 at 05:49

0 Answers0