mongodb Nodejs数组对象未更新

nr7wwzry  于 2023-01-20  发布在  Go
关注(0)|答案(3)|浏览(133)

我正在从mongoose数据库中获取数据。它有一些数组,这些数组有ID,我需要从其他API中获取数据。所有工作都正常,但当我在for循环team[i].teamPlayersDetails = playerss;中像这样更改数组对象时,它没有更改,我甚至可以看到玩家有数据,但它没有更改团队。

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 })
};
xeufq47z

xeufq47z1#

先用瘦肉再检查

let team = await Team.find().lean();
omhiaaxx

omhiaaxx2#

您的逻辑存在缺陷。您在迭代每个player_id时更新team[I].teamPlayersDetails。您应该仅在迭代所有player_id时执行更新。
最好使用map运算符函数将player_id转换为它们各自的细节,因此不需要中间的playerss数组。
如果希望更改反映在数据库中,则应使用updateOneupdateMany收集方法显式执行更新。

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 } });
    }

    // ...
};
sg24os4d

sg24os4d3#

我建议您使用经典的for循环来代替forEach

相关问题