I am getting a data from mongoose database. And It have some array which have ids which data I need to get from other api. All is working but when I change the object of array like this in for loop team[i].teamPlayersDetails = playerss;
Its not changing I can even see playerss have data but its not changing the team.
const getAllTeams = async (req, res) => {
let team = await Team.find();
var userids = [];
var usersdata = [];
for (let i = 0; i < team.length; i++) {
for (let j = 0; j < team[i].teamPlayers.length; j++) {
userids.push(team[i].teamPlayers[j])
}
}
var data = {
'ids': userids
}
await axios.post(`http://localhost:3000/auth/getMultipleUserByUserID`, data)
.then(async function (response) {
usersdata = response.data.data
});
for (let i = 0; i < team.length; i++) {
playerss = [];
team[i].teamPlayers.forEach(player_id => {
playerss.push(usersdata.find(p => p.userID === player_id.toString()))
team[i].teamPlayersDetails = playerss;
})
}
if (!team) {
return res.status(200).json({ message: "user not found", success: false })
}
return res.status(200).json({ message: "success", success: true, data: team })
};
3
Answers
Instead of forEach i suggest you to use classic for loop
You logic has a flaw. You are updating the
team[I].teamPlayersDetails
over eachplayer_id
iterated upon. You should be only performing the update when allplayer_id
s have been iterated.You are better using the
map
operator function to transform theplayer_id
s to their respective details hence no need for the intermediaryplayerss
array.If you would like your changes to be reflected in the database, you should perform the update explicitly using
updateOne
orupdateMany
collection methods.use lean and then check