[Fixed] I does not update the value in the database

Issue

I want to update the number of wins of a team and loses of its opponent.

This is my schema;

const TeamSchema = new mongoose.Schema(
    {
        teamName: {
            type: String,
            required: true,
            trim: true,
            max: 50,
        },
        players: [
            {
                name: {
                    type: String,
                    required: true,
                    trim: true,
                    max: 50,
                },
                jerseyNumber: {
                    type: String,
                    required: true,
                    trim: true,
                },
                scores: {
                    type: Number,
                    default: 0,
                    trim: true,
                },
                fouls: {
                    type: Number,
                    trim: true,
                },
            },
        ],
        gameEvent: {
            type: String,
            required: true,
            enum: ['basketball', 'volleyball', 'soccer'],
        },
        gamesWin: {
            type: Number,
            default: 0,
        },
        gamesLose: {
            type: Number,
            default: 0,
        },
    },
    { timestamps: true }
);

module.exports = mongoose.model('teams', TeamSchema);

Here is my request;

exports.setwinnerTeam = async (req, res) => {
    try {
        const { sub, gameEvent } = req.user;
        const { winner, loser } = req.body;

        const winnerTeamOne = LiveMatch.findOne({
            _id: req.params.id,
            'teamOne._id': mongoose.Types.ObjectId(winner),
            'teamTwo._id': mongoose.Types.ObjectId(loser),
        });
        const winnerTeamTwo = LiveMatch.findOne({
            _id: req.params.id,
            'teamOne._id': mongoose.Types.ObjectId(loser),
            'teamTwo._id': mongoose.Types.ObjectId(winner),
        });

        if (winnerTeamOne) {
            await Team.findOneAndUpdate(
                {
                    _id: mongoose.Types.ObjectId(winner),
                    gameEvent: gameEvent,
                    user: sub,
                },
                {
                    $inc: {
                        gamesWin: 1,
                    },
                }
            );

            await Team.findOneAndUpdate(
                {
                    _id: mongoose.Types.ObjectId(loser),
                    gameEvent: gameEvent,
                    user: sub,
                },
                {
                    $inc: {
                        gamesLose: 1,
                    },
                }
            );

            return res.send({ message: 'Added the win game' });
        }

        if (winnerTeamTwo) {
            await Team.findOneAndUpdate(
                {
                    _id: mongoose.Types.ObjectId(winner),
                    gameEvent: gameEvent,
                    user: sub,
                },
                {
                    $inc: {
                        gamesWin: 1,
                    },
                }
            );

            await Team.findOneAndUpdate(
                {
                    _id: mongoose.Types.ObjectId(loser),
                    gameEvent: gameEvent,
                    user: sub,
                },
                {
                    $inc: {
                        gamesLose: 1,
                    },
                }
            );

            return res.send({ message: 'Added the win game' });
        }
    } catch (error) {
        console.log(error);
        return res.status(400).json({
            message: 'There was a problem adding a score',
        });
    }
};

and here is my call in frontend;

const setWinnerTeamOne = async (winnerOfTeam, loserTeam) => {
        try {
            setwinLoading(true);
            const winnerOfTheGame = {
                winner: winnerOfTeam,
                loser: loserTeam,
            };
            const { data } = await fetchContext.authAxios.patch(
                `facilitator/set-winner-of-the-game/${liveMatch._id}`,
                winnerOfTheGame
            );

            return console.log(data.message);
        } catch (error) {
            const { data } = error.response;
            console.log(data.message);
        }
    };

I suspect that I get that error in findOneAndUpdate but I can’t tell what approach I can use on incrementing the wins and loses.

PS: I updated this question because I figured out that the passed data is not an ID.

Solution

I’m not a 100% sure why your code throws the given error, my first guess is that the ids sent are actually wrong. Please add a console.log before the .findOneAndUpdate calls, to check whether the correct ids were sent or not.

Other than that there are a couple of things to enhance your code.

The findOneAndUpdate call already updates your documents in the database, so you don’t actually need to call .save() after them.

Secondly you don’t need to manually cast ids to ObjectIds, mongoose does that automatically for you.

Thirdly you can replace the findOneAndUpdate calls with findByIdAndUpdate and if you’re not returning the updated results, you can also leave out the new: true option.

You should also place both these calls in a Promise.all() because they don’t depend each other so the request will be answered sooner as the db operations are now running in parallel.

And if data consistency is important to you, you could also use transactions for these operations.

Leave a Reply

(*) Required, Your email will not be published