Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:
I am having issues making the exercise field object literal but seems to be working fine using console.log while testing. Any feedback or assistance would be appreciated

Describe your issue in detail here.

  • The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.

Your project link(s)
https://boilerplate-project-exercisetracker.cashmerefrosh91.repl.co

solution:

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

The failure says when you create an exercise it should return the user object with the exercise fields attached… much like the get request… instead, yours just returns the single exercise you just created;

i tried refactoring the code but still couldn’t get it to work.

app.post(‘/api/users/:_id/exercises’, (req, res) => {
const userId = req.body[‘:_id’];
let exercises = {
description: req.body.description,
duration: Number(req.body.duration),
date: req.body.date
}
if(!userId) (
res.send({ message: “User not found” })
);
if(!exercises.date) {
date = new Date().toDateString();
} else {
date = new Date(exercises.date).toDateString();
}

User.findByIdAndUpdate( userId , {$push: { exercises: exercises } },
{ new: true }, (err, updatedUser) => {
if(err) return console.log(err)

let returnObj = {
username: updatedUser.username,
description: exercises.description,
duration: exercises.duration,
date: exercises.date,
_id: userId,
}

res.send(returnObj)
}
)

})

Well, it seems things have gotten worse. Previously I was able to create exercises and review them. Everything seemed to work well, my previous comment just pointing out the fact that instead of returning the user object, you were just returning the single exercise.

This time it allowed me to create one exersize, but a second one gave me an invalid date error. I tried several more times with no success, and now when I view my exercise logs it shows hundreds of exercise entries all saying invalid date. Something has gone horribly wrong.

image

Based on your code snippet provided, one issue is when you format your date, you’re saving it to a variable date instead of exercises.date meaning it never gets written to your database.

Secondly, I’m guessing maybe your original problem was that you’re replying with res.send. To properly send a JSON object, you should probably use res.json().

See if that helps. If you have further problems I would suggest sharing the link to your Replit (not the application link like above, but the link you use to edit your code as that will allow people to review all the code).