Im stuck at problem 8: “The response returned from POST /api/users/:_id/exercises
will be the user object with the exercise fields added.”
I’ve seen in various topics what might be causing this issue. I’ve tried everything and nothing works. Many solutions indicate that the return value of _id should be of type ObjectId, so I changed it, but it still didn’t work.
This is my “/api/users/:_id/exercises” code:
app.post(“/api/users/:_id/exercises”, async (req, res) => {
try {
// Encontrar o usuário pelo ID
const user = await User.findById(req.params._id);
if (!user) return res.json({ error: “user doesn’t exist” });
// Criar um novo exercício
const newExercise = await Exercise.create({
username: user.username,
description: req.body.description,
duration: req.body.duration,
date: req.body.date ? new Date(req.body.date) : new Date(),
});
// Responder com o objeto do usuário incluindo o novo exercício
return res.json({
username: user.username,
description: newExercise.description,
duration: newExercise.duration,
date: newExercise.date.toDateString(),
_id: user._id, // Mantém o ID como ObjectId
});
} catch (error) {
console.error(error);
return res.json({ error: “Operation failed” });
}
});
Please, somebody, save me!