0

I'm doing a foreach in my nodejs route through a list of items, then after the foreach finishes I render the ejs page. but I'm surprised that I'm receiving some items in a randomly wrong order.

router.get("/history", isLoggedIn, function(req, res) {
  var docs=[];
  Tube.find({}).sort({date: 'desc'}).limit(100).exec((err, tubes) => {



var itemsProcessed = 0;
        var status;

tubes.forEach(async (tube, index, array) => {
     await Box.findOne({ $or: [{"Tubes": tube._id}, {"nok_Tubes": tube._id}]},async function (err, box) {
      if(err || !box) {console.log(err); res.json({message:"failed"});}
      else{
        if(tube.status)
        status=await "ok";
        else if(tube.status===false) status=await "nok";
       await docs.push({qr: tube.qr_code, status, code_bar: box.code_bar, insert_date: moment(tube.date).format("YYYY-M-D H:mm:ss a"), count_in_box: tube.count_in_box });
       }

    }).then(function () {
      itemsProcessed++;
      if(itemsProcessed === array.length) {
        console.log(docs[0]);
        res.render("detection/history", {docs});
      }
    });


});







   });
   
});
med mnari
  • 1
  • 4
  • `Box.findOne` is async. By definition, you don't know how much time is needed to get the response. The `foreach` loop is throwing multiple requests at once to Mongo. You can't tell which response will come first. - What looks the easier would be to re-order the results before the render. – Louys Patrice Bessette Feb 12 '21 at 17:29
  • so I should order them manually? – med mnari Feb 12 '21 at 17:33
  • Based on the `insert_date`... Maybe... Look for a `.sort((a,b)=>{...})` function... – Louys Patrice Bessette Feb 12 '21 at 17:34
  • I have tried this: ``` if(itemsProcessed==tubes.length) { docs=await tubes_docs.sort((a, b) => b.insert_date - a.insert_date); res.render("detection/history", {docs}); } ``` but it still not giving the right order – med mnari Feb 12 '21 at 22:16
  • finally I managed to solve the problem with a another two for loops to order the results by date – med mnari Feb 12 '21 at 22:35

0 Answers0