Exercise tracker - cannot pass 'post exercise' tests

My project adds an exercise and shows the data as per the instructions.
But it doesn’t pass tests 7 and 8 which relate to posting exercises.

I haven’t yet done the coding for the ‘get exercises’.

Please could someone advise what I have done wrong.

my code: boilerplate-project-exercisetracker - Node.js Repl - Replit

Link to the challenge:

The problem with test 7 was caused by a since fixed bug in the test. The problem with test 8 is in your code. You should log the route inputs and responses (right before return res.json(...); and if you do, you won’t see anything logged from your POST exercise route. I double checked by adding a log statement at the end of the route and it hit every time.

You need to add some debug logging to your route and run the tests and then add log statements throughout the route to diagnose your numerous conditionals, since they are not matching like you think they are.

Thank you for replying.

Test 7 is now passing.

I’ve added logs, as you suggested, to my code immediately before and after my save:

console.log(`newExercise:${newExercise}:`);
                    //add
                    newExercise.save(function(err, data) {
console.log(`err after save:${err}:`);

I had no errors when adding my first exercise (for userid 6345930745dc28528ae508f7, description Pullups, duration 10 and date 2022-10-02

But when I try to add another exercise, I get these results:

newExercise:{
  userid: '6345930745dc28528ae508f7',
  description: 'Sit ups',
  duration: 15,
  date: '2022-10-09',
  _id: new ObjectId("6345952e4723342117f83edc")
}:

and

err after save:MongoServerError: E11000 duplicate key error collection: exertrackdb.exercises index: username_1 dup key: { username: null }:

my res.json of the error gives me:

{"error":{"index":0,"code":11000,"keyPattern":{"username":1},"keyValue":{"username":null}}}

I’m afraid I don’t understand the error message - newExercise doesn’t have username so why does it talk about username?

I added the following to both my schema definitions:

, { autoIndex: false }

I also added the following lines to my app.get('/', async (req, res) => {:

await user.syncIndexes();
await exercise.syncIndexes();

I now get the following when I add a new exercise:

{"username":"Alan","description":"Running on the spot","duration":"7","date":"Mon Oct 10 2022","_id":"6345930745dc28528ae508f7"}

But still I cannot pass test 8 - please help

Not sure that it matters for the issue at hand, but duration should be a number and not a string.

Thank you for replying.
I changed my code and now get:

{"username":"Alan","description":"Arm curls","duration":20,"date":"Tue Oct 11 2022","_id":"6345930745dc28528ae508f7"}

Unfortunately it didn’t help - I still can’t pass test 8 :confused:

You need to diagnose why your conditionals are not matching. The linked code above still falls all the way through the route without matching anything and your updates are not there. Adding logging near the top of the POST exercises route before the conditional like

  console.log(`req.body: ${JSON.stringify(req.body)}`)
  console.log(`req.params: ${JSON.stringify(req.params)}`)
  console.log(`req.query: ${JSON.stringify(req.query)}`)
  console.log(JSON.stringify(newExercise));
  console.log(JSON.stringify(error));
  console.log(`id: ${id}`);

yields output like

req.body: {"description":"test","duration":"60","date":"1990-01-01"}
req.params: {"_id":"6345e6975a04561b71f0116d"}
req.query: {}
{"description":"test","duration":60,"date":"1990-01-01","_id":"6345e541b39cb5d75d5c5bfb"}
{"errors":{"userid":{"name":"ValidatorError","message":"Path `userid` is required.","properties":{"message":"Path `userid` is required.","type":"required","path":"userid"},"kind":"required","path":"userid"}},"_message":"exercise validation failed","name":"ValidationError","message":"exercise validation failed: userid: Path `userid` is required."}
id: undefined
missed me

Trace your id variable through that and you’ll find the problem.

Thank you for replying.

I’m not sure what you mean by conditionals.
I don’t get the same results as you.
What does missed me mean?

I tried logging as you suggested:
immediately after app.post('/api/users/:_id/exercises', async function(req, res) {
I put

console.log(`req.body: ${JSON.stringify(req.body)}`);
console.log(`req.params: ${JSON.stringify(req.params)}`);
console.log(`req.query: ${JSON.stringify(req.query)}`);

and these are the results:

req.body: {":_id":"6345930745dc28528ae508f7","description":"Press-ups","duration":"40","date":"2022-10-09"}
req.params: {"_id":"6345930745dc28528ae508f7"}
req.query: {}

Immediately after creating newExercise I put

console.log(JSON.stringify(newExercise));

This is the result:

{"userid":"6345930745dc28528ae508f7","description":"Press-ups","duration":40,"date":"2022-10-09","_id":"6345f5f457dd9608dee16431"}

Immediately after const error = newExercise.validateSync(); which is the only place that error is used, I put

console.log(JSON.stringify(error));

And this is the result:

undefined

Immediately before newExercise.save(function(err, data) { I put

console.log(JSON.stringify(newExercise));

This is the result

{"userid":"6345930745dc28528ae508f7","description":"Press-ups","duration":40,"date":"2022-10-09","_id":"6345f5f457dd9608dee16431"}

Immediately after newExercise.save(function(err, data) { I put

console.log(`err: ${err}`);
console.log(`data:${data}:`);
console.log(`id: ${id}`);

and these are the results:

err: null
data:{
  userid: '6345930745dc28528ae508f7',
  description: 'Press-ups',
  duration: 40,
  date: '2022-10-09',
  _id: new ObjectId("6345f5f457dd9608dee16431"),
  __v: 0
}:
id: 6345930745dc28528ae508f7

I then coded

                        const d = new Date(data.date);
                        res.json({ username   : username,
                                   description: description,
                                   duration   : data.duration,
                                   date       : d.toDateString(),
                                   _id        : id
                                 });

and this is the result

{"username":"Alan","description":"Press-ups","duration":40,"date":"Sun Oct 09 2022","_id":"6345930745dc28528ae508f7"}

I also tried changing the _id : id in the res.json to _id : data.id but this still won’t pass test 8.

if/then/else statements, for instance. The missed me is logged after none of your conditionals are matched.

Indeed. I’m forking your code, adding by mongoDB connection details, adding the logging statements and running the fCC tests against your project. You must be doing something different because this

is not what is passed in to the API by the tests; specifically there is not :_id field in the req.body object from the fCC tests.

Check the logging output after running the fCC tests against your code.

Where do I find the fCC tests?
My html looks like this:
image
I made the :id, description and duration inputs mandatory (so I don’t have to test for them (being blank) in my code).

My index.html has this code:

    <script>
      const exerciseForm = document.getElementById("exercise-form");

      exerciseForm.addEventListener("submit", () => {
        const userId = document.getElementById("uid").value;
        exerciseForm.action = `/api/users/${userId}/exercises`;

        exerciseForm.submit();
      });
    </script>

Doesn’t this mean that the :id input (which has id="uid") is passed across when the Submit button is pressed? I don’t understand why req.body doesn’t include it in the fCC tests.

You linked to them earlier, asking about tests 7 and 8…

You can use and handle any additional fields you want, but the spec says that the user ID will be in the URL parameter _id of /api/users/:_id/exercises and the the exercise information will be in the request body. These are the parameters the tests are using.

Thank you for replying - I really do appreciate your help.

I see where I misunderstood the spec. I have changed the code to fetch the _id from the request parameters and test 8 is now working :slightly_smiling_face: - thank you!

This statement:

is really going to help me solve my issues in the future - I always wondered how people knew what tests fCC was doing.

Thanks again for helping me - very much appreciated (is there a way of rating the help or helpers? - 'cos you would score very high)