0

While working in a web project I am facing this issue:

router.get('/dashboard', isLoggedIn, (req, res) => {
  let userParties = req.user.parties; // array of IDs
  let allParties = [];
  userParties.forEach(function(partyID) {
    Party.find(partyID, function(err, foundParty) {
      if (err) {
        console.log(err);
        res.redirect('/dashboard');
      } else {
        allParties.push(foundParty);
        console.log(foundParty); // Object found successfully
      }
    });
  });
  console.log(allParties); // array remains empty
  res.render('index.ejs', {parties: allParties});
});

I want to fetch the data of all parties attended by the current user. The userParties is an array of party IDs and Party model has all the information like party theme, items, venue etc. Even after succesfuuly getting the party object, after pushing into the array I am getting an empty array. How can I fix this? I want an array of party objects having IDs same as the IDs in userParties array. Database is mongodb.

  • What logged first? foundParty or allPartis? If allParties it could be a synchronous problem. Alert allParties call more early then be written. – Dima Vak May 13 '20 at 07:43
  • You probably want to wait for Party.find() to complete before looping over the next partyID. Look into async/await for the Mongo driver. – Emil Carlsson May 13 '20 at 07:46

0 Answers0