Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:
I double checked that the names of the exercise fields being posted on the html form are the same names being returned in my res.send json object. I still can’t pass test #8 ( The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.)

What am I doing wrong? The code I’m using for now is below:

app.post('/api/users/:_id/exercises', async function(req, res) {
  let { description, duration, date } = req.body;
  const userId = req.body[':_id'];
  const foundUser = await User.findById(userId);

  if(!foundUser) {
    res.json({message: 'No user was found for that id'});
  }
  
  if(!date) {
    date = new Date();
  } else {
    date = new Date(date);
  }

  await Exercise.create({
    username: foundUser.username,
    description,
    duration,
    date,
    userId
  });
  
  res.send({
    username: foundUser.username, 
    description, 
    duration, 
    date: date.toDateString(),
    _id: userId
  });
});

Your project link(s)

solution: boilerplate-project-exercisetracker - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) 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:

You are returning

{"message":"No user was found for that id"}

Which is not correct.

If you want to have the user name unique in the schema you have to check for the opposite and handle that case as an error. So if the same user name is used you send a response for that.


As an aside. The tests are compatible with such a schema but it can sometimes cause issues when developing as you might (for whatever reason) end up with stale or duplicate data (so it throws duplicate key errors). You can always delete the collection (on Atlas) and start fresh if that happens.

1 Like