2

我有这个 updateGameScore 异步服务功能,如果 GameScore 集合中没有具有特定用户 ID 的记录,则用于添加新记录,或者如果存在则更新相关记录:

const updateGameScore = async (userId, gameId, score, date, res) => {

    const gameScore = await GameScore.findOne({ userId });

    //If no record found with given userId, a new record will be created
    if (!gameScore) {
        let newGameScore = new GameScore({
            userId,
            gameScores: { gameId, highScore: score },
            totalScore: score,
            date,
        });

        newGameScore = await newGameScore.save();
    }
    //If there is already a record of the given userID
    else {
        //The totalscore field of that user will be updated by adding the new score to the current total score
        const totalScore = gameScore.totalScore + score;
        await GameScore.findByIdAndUpdate(
            { _id: gameScore._id },
            { totalScore, date }
        );
    }

然后我在 map 函数中调用这个函数,从已经存在的 db 集合中调用 50,000 次。

    allPlayers = await Player.find();
    await allPlayers.map((player) => {
        const userId = player.userId;
        const gameId = player.gameId;
        const score = player.score;
        const date = player.date;

        updateGameScore(userId, gameId, score, date, res);
    });

但是,我的代码 updateGameScore 函数可以正常工作(如果我一一调用)。但是当我一次调用 50,000 条记录时,所有记录都会并行调用此函数,并在我的 GameScore 集合中创建 50,000 条新记录,我不需要这样做。如果具有给定 userId 的记录不存在,我只需要创建新记录,但如果具有给定 ID 的记录存在,则更新记录。如果我的地图函数按顺序调用 updateGameScore 函数,这将正常工作,但不幸的是它没有。请帮我解决这个问题,因为我对异步 js 的了解非常少。

4

0 回答 0