简体   繁体   中英

How to fetch data in MongoDB as Catgepory > Sub Catgeory > Product using nodejs

I have 3 different models which relates each other i want to join them by Id. the response which i want is given below

Please find below sample data:

I want this type of json in response

      "categoryData": [
    {
    "_id": "5f227a756c42fe34e883be3c",
    "categoryName": "Cake",
    "categoryDescription": "Cake",
    "IsActive": true,
    "EnteredBy": null,
    "WhenEntered": "2020-07-30T07:44:52.409Z",
    "ModifiedBy": null,
    "WhenModified": null,
    "__v": 0,
    "subcategorydata": [
    {
    "_id": "5f23c85d3926134528cb8208",
    "categoryId": "5f227a756c42fe34e883be3c",
    "subcategoryName": "SugerFree Cake",
    "subcategoryDescription": "SugerFree Cake",
    "IsActive": true,
    "EnteredBy": null,
    "WhenEntered": "2020-07-31T07:29:33.829Z",
    "ModifiedBy": null,
    "WhenModified": null,
    "__v": 0,
    "ProductData": [
    {
    "_id": "5f23c83e3926134528cb8207",
    "ProductName": "Eggless Cake",
    "ProductDescription": "Eggless Cake",
    "IsActive": true,
    "EnteredBy": null,
    "WhenEntered": "2020-07-31T07:29:02.877Z",
    "ModifiedBy": null,
    "WhenModified": null,
    "__v": 0
    },
    {
    "_id": "5f23c83e3926134528cb8207",
    "ProductName": "Eggless Cake",
    "ProductDescription": "Eggless Cake",
    "IsActive": true,
    "EnteredBy": null,
    "WhenEntered": "2020-07-31T07:29:02.877Z",
    "ModifiedBy": null,
    "WhenModified": null,
    "__v": 0
    },
    }}

Please help me in this..Thank you.

Refer MONGO AGGREGATION LOOKUP

db.category.aggregate([
   {
     $lookup:
       {
         from: "subcategory",
         localField: "_id",
         foreignField: "categoryId",
         as: "subcategory_items"
       }
  }
])

For Further Reference: MULTIPLE COLLECTION JOIN QUERY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM