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.