Возврат одного объекта

#javascript #node.js #json #express

#javascript #node.js #json #выразить

Вопрос:

Я пытался сделать это несколько дней назад.

Я хочу сделать запрос, который получает все компании, зарегистрированные в одном городе, после этого для каждого бизнеса я хотел бы получить все продукты в бизнесе и, наконец, сохранить его в новом объекте и отправить его в качестве ответа на интерфейс.

Это код, который я использую:

 router.get('/app/list-all-products-city', async(req, res, next) => {
  var AddProduct;
  var Result;
  console.log(req.body);
  try {
    _business = await Business.find({
      businessCity: 'Departamento de Cochabamba'
    });
  } catch (e) {
    console.log(e);
    res.status(500).send('hubo un error, algo malio sal');
  }
  try {
    for (i in _business) {
      let Products = await Product.find({
        productInBusiness: _business[i]['_id']
      });
      for (index in Products) {
        if (Products.hasOwnProperty(index)) {
          console.log(Products[index].productName);
          AddProduct = {
            AddProduct,
            ...Products
          };
        }
      }
    }
    res.json(AddProduct);
  } catch (e) {
    console.log(e);
    res.status(500).send('hubo un error, algo malio sal');
  }
});
  

но, к сожалению, я получаю вложенный объект, который является этим:

 {
  "0": {
    "productStatus": 1,
    "productTags": "2020-08-03 23:14",
    "productPerCentPromo": 0,
    "productCreationDate": "2020-08-03 23:14",
    "_id": "5f2a183a8360400063020c8f",
    "productName": "Util",
    "productInBusiness": "5f2a15c38360400063020c8d",
    "productCategory": "5f1bad9ebbf8a71eb730baf7",
    "productSubCategory": "5f2a16eb8360400063020c8e",
    "productDetails": "Limpieza de superficies de cocina ",
    "productUnitSale": "Botella",
    "productSalePrice": 25,
    "productStock": 50,
    "ProductImage001": "A1LmqJaHtXC6KETKxehjf.jpg",
    "ProductImage002": "gYsYqHMvP79eBcFUjeYqxz.jpg",
    "ProductImage003": "trpgfZPfX41rbJh5z7H1nr.jpg",
    "__v": 0
  },
  "AddProduct": {
    "0": {
      "productStatus": 1,
      "productTags": "2020-08-02 14:16",
      "productPerCentPromo": 0,
      "productCreationDate": "2020-08-02 14:16",
      "_id": "5f272901569c9700523bbcca",
      "productName": "Zapatón de lana",
      "productInBusiness": "5f2723f8569c9700523bbcc6",
      "productCategory": "5f1bb0f4bbf8a71eb730baf9",
      "productSubCategory": "5f26e548569c9700523bbcbe",
      "productDetails": "Zapatones de lana tejidos a crochet, con suela antideslizante.",
      "productUnitSale": "Par",
      "productSalePrice": 40,
      "productStock": 3,
      "ProductImage001": "ufyagH39yatG1ypQDNTPG8.jpg",
      "ProductImage002": "dRCyVqRFsPaYssUBp5Cugo.jpg",
      "ProductImage003": "erMXW5n1epo11CEyASjCM.jpg",
      "__v": 0
    },
    "AddProduct": {
      "0": {
        "productStatus": 1,
        "productTags": "2020-08-02 14:16",
        "productPerCentPromo": 0,
        "productCreationDate": "2020-08-02 14:16",
        "_id": "5f2716f1569c9700523bbcc4",
        "productName": "Latitude 3400 Business Laptop",
        "productInBusiness": "5f2715c9569c9700523bbcc3",
        "productCategory": "5f1bb62abbf8a71eb730bafb",
        "productSubCategory": "5f1c861e72a9f59686f5fd68",
        "productDetails": "Dell Latitude 3000 3400 14" Notebook - 1920 x 1080 - Core i5 i5-8265U - 8 GB RAM - 256 GB SSD - Windows 10 Pro 64-bit - Intel UHD Graphics 620 - English (US) Keyboard - Bluetooth",
        "productUnitSale": "Unidad",
        "productSalePrice": 10455,
        "productStock": 3,
        "ProductImage001": "xAW2zhRVrPskVCxHf23L3X.jpg",
        "ProductImage002": "c3nZcJiaTtNUyV5DdMymtd.jpg",
        "ProductImage003": "fn5Qi86mexerHosVwy9c9Z.jpg",
        "__v": 0
      },
      "1": {
        "productStatus": 1,
        "productTags": "2020-08-02 14:16",
        "productPerCentPromo": 0,
        "productCreationDate": "2020-08-02 14:16",
        "_id": "5f271ace569c9700523bbcc5",
        "productName": "Apple MacBook Pro (13 pulgadas)",
        "productInBusiness": "5f2715c9569c9700523bbcc3",
        "productCategory": "5f1bb62abbf8a71eb730bafb",
        "productSubCategory": "5f1c861e72a9f59686f5fd68",
        "productDetails": "Tenth-generation quad-core Intel Core i5 processor Brilliant Retina display with True Tone technology Backlit Magic Keyboard Touch Bar and Touch ID Intel Iris Plus Graphics Ultrafast SSD Four Thunderbolt 3 (USB-C) ports",
        "productUnitSale": "Unidad",
        "productSalePrice": 135940,
        "productStock": 5,
        "ProductImage001": "wn2d18DCSbzRkxG4ZZaBY2.jpg",
        "ProductImage002": "wxtujJ3YLxbY2UjnXzujP6.jpg",
        "ProductImage003": "bJS75Zzi4HSskff9i17Z4D.jpg",
        "__v": 0
      },
      "2": {
        "productStatus": 1,
        "productTags": "2020-08-03 23:14",
        "productPerCentPromo": 0,
        "productCreationDate": "2020-08-03 23:14",
        "_id": "5f2a2d618360400063020c90",
        "productName": "2020 HP Stream 11.6 pulgadas portátil, Intel Atom x5 E8000 hasta 2.0 GHz",
        "productInBusiness": "5f2715c9569c9700523bbcc3",
        "productCategory": "5f1bb62abbf8a71eb730bafb",
        "productSubCategory": "5f1c861e72a9f59686f5fd68",
        "productDetails": "【Office 365 Included】One year of Microsoft Office 365 included ($70 Value). 11.6 inch diagonal HD SVA anti-glare WLED-backlit (1366 x 768), Intel HD Graphics 【Quad-Core Atom x5-E8000】Intel Atom x5-E8000 (1.04 GHz base frequency, up to 2.0 GHz, 2 MB cache, 4 cores), 2-cell, 37.69 Wh Li-ion, up to 12 hours battery life mixed-use 【High Speed】RAM is upgraded to 4GB DDR3L memory for multitasking Adequate high-bandwidth RAM to smoothly run multiple applications and browser tabs all at once 【Enormous Space】Hard Drive is upgraded to 64GB eMMC provides massive storage space for huge files, so that you can store important digital data and work your way through it with ease. Enhance the overall performance of the laptop for business, student, daily usage 【Authorized NexiGo Bundle】 Bundled with NexiGo 32GB MicroSD Card, offers cost-effective portable solution instantly boosting available storage space for your laptop, Authorized Sellers ONLY. 2 x USB 3.1 Gen 1, 1 x USB 3.1 Type-C, 1 x HDMI 1.4, 1 x headphone/microphone combo",
        "productUnitSale": "Unidad",
        "productSalePrice": 2500,
        "productStock": 10,
        "ProductImage001": "nduaWJqGGVvB9jHMTh3sna.jpg",
        "ProductImage002": "ih3XJ8NXuqiaBJonGoKcDP.jpg",
        "ProductImage003": "vuY1GtAP4pmcduD7YwZpCb.jpg",
        "__v": 0
      },
      "AddProduct": {
        "0": {
          "productStatus": 1,
          "productTags": "2020-08-02 14:16",
          "productPerCentPromo": 0,
          "productCreationDate": "2020-08-02 14:16",
          "_id": "5f2716f1569c9700523bbcc4",
          "productName": "Latitude 3400 Business Laptop",
          "productInBusiness": "5f2715c9569c9700523bbcc3",
          "productCategory": "5f1bb62abbf8a71eb730bafb",
          "productSubCategory": "5f1c861e72a9f59686f5fd68",
          "productDetails": "Dell Latitude 3000 3400 14" Notebook - 1920 x 1080 - Core i5 i5-8265U - 8 GB RAM - 256 GB SSD - Windows 10 Pro 64-bit - Intel UHD Graphics 620 - English (US) Keyboard - Bluetooth",
          "productUnitSale": "Unidad",
          "productSalePrice": 10455,
          "productStock": 3,
          "ProductImage001": "xAW2zhRVrPskVCxHf23L3X.jpg",
          "ProductImage002": "c3nZcJiaTtNUyV5DdMymtd.jpg",
          "ProductImage003": "fn5Qi86mexerHosVwy9c9Z.jpg",
          "__v": 0
        },
        "1": {
          "productStatus": 1,
          "productTags": "2020-08-02 14:16",
          "productPerCentPromo": 0,
          "productCreationDate": "2020-08-02 14:16",
          "_id": "5f271ace569c9700523bbcc5",
          "productName": "Apple MacBook Pro (13 pulgadas)",
          "productInBusiness": "5f2715c9569c9700523bbcc3",
          "productCategory": "5f1bb62abbf8a71eb730bafb",
          "productSubCategory": "5f1c861e72a9f59686f5fd68",
          "productDetails": "Tenth-generation quad-core Intel Core i5 processor Brilliant Retina display with True Tone technology Backlit Magic Keyboard Touch Bar and Touch ID Intel Iris Plus Graphics Ultrafast SSD Four Thunderbolt 3 (USB-C) ports",
          "productUnitSale": "Unidad",
          "productSalePrice": 135940,
          "productStock": 5,
          "ProductImage001": "wn2d18DCSbzRkxG4ZZaBY2.jpg",
          "ProductImage002": "wxtujJ3YLxbY2UjnXzujP6.jpg",
          "ProductImage003": "bJS75Zzi4HSskff9i17Z4D.jpg",
          "__v": 0
        },
        "2": {
          "productStatus": 1,
          "productTags": "2020-08-03 23:14",
          "productPerCentPromo": 0,
          "productCreationDate": "2020-08-03 23:14",
          "_id": "5f2a2d618360400063020c90",
          "productName": "2020 HP Stream 11.6 pulgadas portátil, Intel Atom x5 E8000 hasta 2.0 GHz",
          "productInBusiness": "5f2715c9569c9700523bbcc3",
          "productCategory": "5f1bb62abbf8a71eb730bafb",
          "productSubCategory": "5f1c861e72a9f59686f5fd68",
          "productDetails": "【Office 365 Included】One year of Microsoft Office 365 included ($70 Value). 11.6 inch diagonal HD SVA anti-glare WLED-backlit (1366 x 768), Intel HD Graphics 【Quad-Core Atom x5-E8000】Intel Atom x5-E8000 (1.04 GHz base frequency, up to 2.0 GHz, 2 MB cache, 4 cores), 2-cell, 37.69 Wh Li-ion, up to 12 hours battery life mixed-use 【High Speed】RAM is upgraded to 4GB DDR3L memory for multitasking Adequate high-bandwidth RAM to smoothly run multiple applications and browser tabs all at once 【Enormous Space】Hard Drive is upgraded to 64GB eMMC provides massive storage space for huge files, so that you can store important digital data and work your way through it with ease. Enhance the overall performance of the laptop for business, student, daily usage 【Authorized NexiGo Bundle】 Bundled with NexiGo 32GB MicroSD Card, offers cost-effective portable solution instantly boosting available storage space for your laptop, Authorized Sellers ONLY. 2 x USB 3.1 Gen 1, 1 x USB 3.1 Type-C, 1 x HDMI 1.4, 1 x headphone/microphone combo",
          "productUnitSale": "Unidad",
          "productSalePrice": 2500,
          "productStock": 10,
          "ProductImage001": "nduaWJqGGVvB9jHMTh3sna.jpg",
          "ProductImage002": "ih3XJ8NXuqiaBJonGoKcDP.jpg",
          "ProductImage003": "vuY1GtAP4pmcduD7YwZpCb.jpg",
          "__v": 0
        },
        "AddProduct": {
          "0": {
            "productStatus": 1,
            "productTags": "2020-08-02 14:16",
            "productPerCentPromo": 0,
            "productCreationDate": "2020-08-02 14:16",
            "_id": "5f2716f1569c9700523bbcc4",
            "productName": "Latitude 3400 Business Laptop",
            "productInBusiness": "5f2715c9569c9700523bbcc3",
            "productCategory": "5f1bb62abbf8a71eb730bafb",
            "productSubCategory": "5f1c861e72a9f59686f5fd68",
            "productDetails": "Dell Latitude 3000 3400 14" Notebook - 1920 x 1080 - Core i5 i5-8265U - 8 GB RAM - 256 GB SSD - Windows 10 Pro 64-bit - Intel UHD Graphics 620 - English (US) Keyboard - Bluetooth",
            "productUnitSale": "Unidad",
            "productSalePrice": 10455,
            "productStock": 3,
            "ProductImage001": "xAW2zhRVrPskVCxHf23L3X.jpg",
            "ProductImage002": "c3nZcJiaTtNUyV5DdMymtd.jpg",
            "ProductImage003": "fn5Qi86mexerHosVwy9c9Z.jpg",
            "__v": 0
          },
          "1": {
            "productStatus": 1,
            "productTags": "2020-08-02 14:16",
            "productPerCentPromo": 0,
            "productCreationDate": "2020-08-02 14:16",
            "_id": "5f271ace569c9700523bbcc5",
            "productName": "Apple MacBook Pro (13 pulgadas)",
            "productInBusiness": "5f2715c9569c9700523bbcc3",
            "productCategory": "5f1bb62abbf8a71eb730bafb",
            "productSubCategory": "5f1c861e72a9f59686f5fd68",
            "productDetails": "Tenth-generation quad-core Intel Core i5 processor Brilliant Retina display with True Tone technology Backlit Magic Keyboard Touch Bar and Touch ID Intel Iris Plus Graphics Ultrafast SSD Four Thunderbolt 3 (USB-C) ports",
            "productUnitSale": "Unidad",
            "productSalePrice": 135940,
            "productStock": 5,
            "ProductImage001": "wn2d18DCSbzRkxG4ZZaBY2.jpg",
            "ProductImage002": "wxtujJ3YLxbY2UjnXzujP6.jpg",
            "ProductImage003": "bJS75Zzi4HSskff9i17Z4D.jpg",
            "__v": 0
          },
          "2": {
            "productStatus": 1,
            "productTags": "2020-08-03 23:14",
            "productPerCentPromo": 0,
            "productCreationDate": "2020-08-03 23:14",
            "_id": "5f2a2d618360400063020c90",
            "productName": "2020 HP Stream 11.6 pulgadas portátil, Intel Atom x5 E8000 hasta 2.0 GHz",
            "productInBusiness": "5f2715c9569c9700523bbcc3",
            "productCategory": "5f1bb62abbf8a71eb730bafb",
            "productSubCategory": "5f1c861e72a9f59686f5fd68",
            "productDetails": "【Office 365 Included】One year of Microsoft Office 365 included ($70 Value). 11.6 inch diagonal HD SVA anti-glare WLED-backlit (1366 x 768), Intel HD Graphics 【Quad-Core Atom x5-E8000】Intel Atom x5-E8000 (1.04 GHz base frequency, up to 2.0 GHz, 2 MB cache, 4 cores), 2-cell, 37.69 Wh Li-ion, up to 12 hours battery life mixed-use 【High Speed】RAM is upgraded to 4GB DDR3L memory for multitasking Adequate high-bandwidth RAM to smoothly run multiple applications and browser tabs all at once 【Enormous Space】Hard Drive is upgraded to 64GB eMMC provides massive storage space for huge files, so that you can store important digital data and work your way through it with ease. Enhance the overall performance of the laptop for business, student, daily usage 【Authorized NexiGo Bundle】 Bundled with NexiGo 32GB MicroSD Card, offers cost-effective portable solution instantly boosting available storage space for your laptop, Authorized Sellers ONLY. 2 x USB 3.1 Gen 1, 1 x USB 3.1 Type-C, 1 x HDMI 1.4, 1 x headphone/microphone combo",
            "productUnitSale": "Unidad",
            "productSalePrice": 2500,
            "productStock": 10,
            "ProductImage001": "nduaWJqGGVvB9jHMTh3sna.jpg",
            "ProductImage002": "ih3XJ8NXuqiaBJonGoKcDP.jpg",
            "ProductImage003": "vuY1GtAP4pmcduD7YwZpCb.jpg",
            "__v": 0
          }
        }
      }
    }
  }
}
  

Комментарии:

1. вы должны вернуть массив объектов.

2. Я попробовал несколько комбинаций… даже я использовал один объект.assing, и это не сработало addProduct = Object.assign({addProduct}, Products); и никакого успеха… Честно говоря, я схожу с ума от этого…

3. @MarceSanchezMelgar какая библиотека БД здесь используется? изучали ли вы варианты быстрой загрузки в библиотеке БД?

Ответ №1:

Ошибка: здесь снова добавляются одни и те же данные и снова создается вложенный объект.

   AddProduct = {
            AddProduct,
            ...Products
       };
  

пример :

   var a = {"ch":"a"}
  var b = { "test": "a" }
  a = {
     a,
     ...b
  }
  a = {
     a,
   ...b
}
  

Вместо этого добавьте данные в массив и отправьте их.

     for (index in Products) {
        if (Products.hasOwnProperty(index)) {
          console.log(Products[index].productName);
          AddProduct.push(Products)        
          };
        }
      }
    }

output :
[ {
"0": {
    "productStatus": 1,
    "productTags": "2020-08-03 23:14",
    "productPerCentPromo": 0,
    "productCreationDate": "2020-08-03 23:14",
    "_id": "5f2a183a8360400063020c8f",
    "productName": "Util",
    "productInBusiness": "5f2a15c38360400063020c8d",
    "productCategory": "5f1bad9ebbf8a71eb730baf7",
    "productSubCategory": "5f2a16eb8360400063020c8e",
    "productDetails": "Limpieza de superficies de cocina ",
    "productUnitSale": "Botella",
    "productSalePrice": 25,
    "productStock": 50,
    "ProductImage001": "A1LmqJaHtXC6KETKxehjf.jpg",
    "ProductImage002": "gYsYqHMvP79eBcFUjeYqxz.jpg",
    "ProductImage003": "trpgfZPfX41rbJh5z7H1nr.jpg",
    "__v": 0
  },
"1": {
        "productStatus": 1,
        "productTags": "2020-08-02 14:16",
        "productPerCentPromo": 0,
        "productCreationDate": "2020-08-02 14:16",
        "_id": "5f271ace569c9700523bbcc5",
        "productName": "Apple MacBook Pro (13 pulgadas)",
        "productInBusiness": "5f2715c9569c9700523bbcc3",
        "productCategory": "5f1bb62abbf8a71eb730bafb",
        "productSubCategory": "5f1c861e72a9f59686f5fd68",
        "productDetails": "Tenth-generation quad-core Intel Core i5 processor Brilliant Retina display with True Tone technology Backlit Magic Keyboard Touch Bar and Touch ID Intel Iris Plus Graphics Ultrafast SSD Four Thunderbolt 3 (USB-C) ports",
        "productUnitSale": "Unidad",
        "productSalePrice": 135940,
        "productStock": 5,
        "ProductImage001": "wn2d18DCSbzRkxG4ZZaBY2.jpg",
        "ProductImage002": "wxtujJ3YLxbY2UjnXzujP6.jpg",
        "ProductImage003": "bJS75Zzi4HSskff9i17Z4D.jpg",
        "__v": 0
      },
]
   
  

Комментарии:

1. Спасибо, но это не сработало. Ошибка типа: не удается прочитать свойство ‘push’ неопределенного

2. var addProduct = []

3. сделайте его массивом и используйте его.

4. Отличный приятель!! Это сработало, на самом деле мне пришлось внести небольшую модификацию в строку puhs: addProduct.push(Products[index]);

Ответ №2:

Я думаю, вам следует изменить

 console.log(Products[index].productName);
          AddProduct = {
            AddProduct,
            ...Products
          };
  

Для

 console.log(Products[index].productName);
          AddProduct = {
            ...AddProduct,
            ...Products
          };