Introduction:
I am facing a problem when creating a bet in my Node.js application. The code related to the POST route /api/bets
is generating an error that I cannot resolve.
Relevant Code:
Here is the relevant code snippet from the POST /api/bets
route:
const express = require("express");
const router = express.Router();
const Bet = require("../models/bet");
const Game = require("../models/game");
const Odd = require("../models/odd");
const User = require("../models/user");
const handleError = (res, statusCode, errorMessage) => {
console.error(errorMessage);
res.status(statusCode).json({ error: errorMessage });
};
const verifyGameExists = async (gameId) => {
const game = await Game.findById(gameId);
if (!game) throw "Jogo não encontrado.";
};
const verifyOddExists = async (oddId) => {
const odd = await Odd.findById(oddId);
if (!odd) throw "Odd não encontrada.";
};
const verifyUserBalance = async (userId, betAmount) => {
try {
console.log('Verificando saldo do usuário. UserID:', userId);
const user = await User.findById(userId);
console.log('User encontrado:', user);
if (!user || !user.balance || user.balance < betAmount) {
console.log('Saldo insuficiente. User ou balance inválido.');
throw "Saldo insuficiente para a aposta.";
}
} catch (error) {
console.error(`Erro ao verificar o saldo do usuário: ${error}`);
throw `Erro ao verificar o saldo do usuário: ${error}`;
}
};
router.get("/", async (req, res) => {
try {
const bets = await Bet.find({ userId: req.user._id })
.populate({
path: "gameId",
select: "name dateTime teamA teamB",
})
.populate({
path: "oddId",
select: "teamAOdd teamBOdd drawOdd",
});
const formattedBets = bets.map((bet) => ({
betId: bet._id ? bet._id.toString() : null,
gameId: bet.gameId,
oddId: bet.oddId,
betAmount: bet.betAmount,
betType: bet.betType,
status: bet.status,
dateTime: bet.dateTime,
}));
res.status(200).json(formattedBets);
} catch (error) {
handleError(res, 500, "Erro ao obter a lista de apostas.");
}
});
router.post("/", async (req, res) => {
try {
const { gameId, oddId, betAmount, betType } = req.body;
console.log('User object in create bet route:', req.user);
console.log('OddId in create bet route:', oddId);
if (!req.user || !req.user.userId) {
console.log('User ID not defined. Sending error response.');
return handleError(
res,
500,
"Erro ao criar a aposta: ID do usuário não está definido."
);
}
// Verificar se a Odd existe
const odd = await Odd.findById(oddId);
console.log('Response from database:', odd);
console.log('Odd found:', odd);
if (!odd) {
console.log('Odd not found. Sending error response.');
return handleError(
res,
404,
"Erro ao criar a aposta: Odd não encontrada."
);
}
await verifyGameExists(gameId);
await verifyOddExists(oddId);
await verifyUserBalance(req.user.userId, betAmount);
const userId = req.user && req.user._id.toString();
console.log('UserID ao criar aposta:', userId);
const newBet = new Bet({
userId,
gameId,
oddId,
betAmount,
betType,
status: "pending",
dateTime: new Date(),
});
console.log('Objeto da Nova Aposta:', newBet);
await newBet.save();
const user = await User.findById(req.user._id);
const userBalance = user.balance;
const updatedBalance = userBalance - betAmount;
await User.findByIdAndUpdate(req.user._id, { balance: updatedBalance });
res
.status(201)
.json({
message: "Aposta criada com sucesso.",
betId: newBet._id.toString(),
});
} catch (error) {
handleError(res, 500, `Erro ao criar a aposta: ${error}`);
}
});
module.exports = router;
Console
Servidor rodando na porta 3000
Token recebido: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NTVlMjk2MzRhZGRjNjMyMTUxNDM4ZjIiLCJpYXQiOjE3MDA3NzI2MDMsImV4cCI6MTcwMDc3NjIwM30.qg56kCr8OjRr3NFTq9m83Ft-OCmwBz4yHaW8QrPyAns
Token verificado com sucesso. Usuário: {
userId: '655e29634addc632151438f2',
iat: 1700772603,
exp: 1700776203
}
User object in create bet route: {
userId: '655e29634addc632151438f2',
iat: 1700772603,
exp: 1700776203
}
OddId in create bet route: 655c860bfb66e6a152662866
Response from database: {
_id: new ObjectId('655c860bfb66e6a152662866'),
gameId: new ObjectId('6557a8c7650c8c58682b46c8'),
teamAOdd: 2.5,
teamBOdd: 1.8,
drawOdd: 3,
__v: 0
}
Odd found: {
_id: new ObjectId('655c860bfb66e6a152662866'),
gameId: new ObjectId('6557a8c7650c8c58682b46c8'),
teamAOdd: 2.5,
teamBOdd: 1.8,
drawOdd: 3,
__v: 0
}
Verificando saldo do usuário. UserID: 655e29634addc632151438f2
User encontrado: {
_id: new ObjectId('655e29634addc632151438f2'),
username: 'Diogo Pimenta',
password: '$2a$10$4/yOtaQAW.W5A8sN2Y4a4.0SWm5s839HogIFQFjTzy2z9FJwFx1ya',
role: 'user',
balance: 1000,
__v: 0
}
Erro ao criar a aposta: TypeError: Cannot read properties of undefined (reading 'toString')
Problem description:
When trying to create a bet, I get an error TypeError: Cannot read properties of undefined (reading ‘toString’). I am having difficulty identifying the root cause of the problem.
Ambiente:
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
The expected behavior was for the bet to be created successfully, but the mentioned error is occurring, preventing the operation from completing.