首页 > 解决方案 > 如何在 MongoDB 中以 Catgepory > Sub Catgeory > Product 使用 nodejs 获取数据

问题描述

我有 3 个相互关联的不同模型,我想通过 ID 加入它们。我想要的回应如下

请在下面找到示例数据:

我想要这种类型的 json 作为响应

      "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
    },
    }}

请在这方面帮助我。谢谢。

标签: node.jsarraysmongodbmongoosemongodb-query

解决方案


请参阅MONGO 聚合查找

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

供进一步参考:多集合连接查询


推荐阅读