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 })
};
CodePudding user response:
You logic has a flaw. You are updating the team[I].teamPlayersDetails
over each player_id
iterated upon. You should be only performing the update when all player_id
s have been iterated.
You are better using the map
operator function to transform the player_id
s to their respective details hence no need for the intermediary playerss
array.
If you would like your changes to be reflected in the database, you should perform the update explicitly using updateOne
or updateMany
collection methods.
const getAllTeams = async (req, res) => {
let team = await Team.find();
const userids = [];
for (let i = 0; i < team.length; i ) {
for (let j = 0; j < team[i].teamPlayers.length; j ) {
userids.push(team[i].teamPlayers[j]);
}
}
const usersResponse = await axios.post(`http://localhost:3000/auth/getMultipleUserByUserID`, { 'ids': userids });
const usersdata = usersResponse.data.data;
for (let i = 0; i < team.length; i ) {
const teamPlayersDetails = team[i].teamPlayers.map(player_id => usersdata.find(p => p.userID === player_id.toString()));
await Team.updateOne({ _id: team[I]._id.toString() }, { $set: { teamPlayersDetails } });
}
// ...
};
CodePudding user response:
Instead of forEach i suggest you to use classic for loop