0

So the code I'm working with is as follows:

// get user team
exports.getTeam = (req, res) => {
  let team = [];
  db.doc(`/users/${req.user.username}`)
    .get()
    .then((doc) => {
      doc.data().players.forEach(player => {
        db.doc(`/players/${player}`).get()
        .then(data => {
          team.push(data.data());
        });
      })
    })
    .then(() => {
      res.json(team);
    })
    .catch((err) => console.error(err));
};

Basically my app has a user that can add players to their team, the players database id's are stored as an array on a 'players' property for the user, and when the user views their team I want to display their team by grabbing the user by their username (which is included in their requests via some auth middleware/token authentication), then loop through the players array of the user, add the player to the 'teams' array, and then return the teams array. I have tried console.logging at various stages and can confirm the following:

  • I am accessing the user, the players array (doc.data().players), and the actual player documents correctly (they all return exactly what I would expect if I console.log at different points in the code)
  • returning the team within the forEach loop only returns with one value, as would be expected

I have also tried declaring 'team = []' at different points (for example, after the first .then((doc)=>...) and it doesn't make a difference. I suspect the issue with accessing the complete team array has something to do with the second then statement that occurs after getting a player in the forEach loop. A then within a then seems fishy.

Any help welcomed, please let me know if more info is required.

Tim
  • 1
  • 3
  • You need to wait for all the `db.doc(\`/players/${player}\`).get()` promises to resolve. See the `Promise.all` example in [this answer](https://stackoverflow.com/a/43766002/283366) – Phil Jun 24 '20 at 01:21
  • 1
    @Phil Awesome thank you. That helped point me in the right direction (Promises) and then this video: https://www.youtube.com/watch?v=d9GrysWH1Lc helped get me where I needed to go. Thank you again. – Tim Jun 24 '20 at 02:00

0 Answers0