简体   繁体   中英

Pushing values to array

router.get("/api/cart", auth, async (req, res) => {
  try {
    const user = await User.findById(req.user._id);
    items = [];
    await user.cartProducts.forEach(async (product) => {
      var item = await Item.findById(product._id);
      items.push(item);
      console.log(items);
    });
    console.log(items)
    res.send(items);
  } catch (e) {
    res.status(500).send(e);
  }
});

I want to send the data of the all the products selected by the user back in the array. The first console log shows the array with the products. While, the second shows the empty array. Moreover, api is working good no issues with it. Personally, I think issue is with my javascript concepts.

await doesn't work with .forEach . You need to use for :

items = [];

for(let product of user.cartProducts) {
   let item = await Item.findById(product._id);
   items.push(item);
}
console.log(items)
res.send(items);

EDIT:

Also, this method is going to kill your database. If you need to fetch 100 products, then you're doing 100 requests to the DB.

You can achieve the same result in one request:

const ids = user.cartProducts.map( p => p._id ); // Array of _id

const items = await Item.find({
    _id : {
         $in : ids
    })
    .lean() // Returns simple JSON, faster

this will helpful to you to push selected values

 $(document).ready(function () { var tmp = []; $("input[name='checkbox']").change(function() { var checked = $(this).val(); if ($(this).is(':checked')) { tmp.push(checked); }else{ tmp.splice($.inArray(checked, tmp),1); } }); $('#button').on('click', function () { alert(tmp); }); });
 <input name="checkbox" value="1" type="checkbox" /> <input name="checkbox" value="2" type="checkbox" /> <input name="checkbox" value="3" type="checkbox" /> <input name="checkbox" value="4" type="checkbox" /> <button id="button" type="button">button</button>

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