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});
}
});
});
});
});