Exercise Tracker: I failed to pass GET /api/users/:id/logs

Hello,

I found I failed to pass every sub tests relating GET /api/users/:id/logs in Exercise Tracker test.
Even though it looks like I’ve got seemingly the same result with the example.

I’ve uploaded my work to github.
I’ll appreciate if anyone has a chance to look into my work.

Try to console.log your duration and description. If the duration is 60 and description is 'test' you should be good. This is what they required in their validation tester:

const expected = {
username,
description: ‘test’,
duration: 60,
_id,
date: new Date().toDateString()
};

See the test validator from FCC in their Github account.

You have to log your responses and your errors where you are checking for them. Logging your GET log routes produces:

req.body: {}
req.params: {"id":"624c23d87aa3bcc4a7584b8c"}
req.query: {}
{
  username: 'fcc_test_16491570805',
  count: 0,
  _id: new ObjectId("624c23d87aa3bcc4a7584b8c"),
  log: []
}

for example, so nothing in the logs. Logging the errors and output for the POST exercise route yields the error:

Error: exercise validation failed: date: Cast to date failed for value "Invalid Date" (type Date) at path "date"
    at ValidationError.inspect (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/error/validation.js:48:26)
    at internal/per_context/primordials.js:23:32
    at formatValue (internal/util/inspect.js:762:19)
    at inspect (internal/util/inspect.js:328:10)
    at formatWithOptions (internal/util/inspect.js:1989:40)
    at console.value (internal/console/constructor.js:316:14)
    at console.warn (internal/console/constructor.js:349:61)
    at /home/runner/project-exercisetracker-freecodecamp/server.js:71:19
    at /home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/model.js:5001:18
    at processTicksAndRejections (internal/process/task_queues.js:79:11) {
  errors: {
    date: CastError: Cast to date failed for value "Invalid Date" (type Date) at path "date"
        at SchemaDate.cast (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/schema/date.js:354:11)
        at SchemaDate.SchemaType.applySetters (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/schematype.js:1179:12)
        at model.$set (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/document.js:1409:20)
        at model.$set (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/document.js:1143:16)
        at model.Document (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/document.js:162:12)
        at model.Model (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/model.js:109:12)
        at new model (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/model.js:4833:15)
        at /home/runner/project-exercisetracker-freecodecamp/server.js:62:27
        at /home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/model.js:5001:18
        at processTicksAndRejections (internal/process/task_queues.js:79:11) {
      stringValue: '"Invalid Date"',
      messageFormat: undefined,
      kind: 'date',
      value: Invalid Date,
      path: 'date',
      reason: AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
      
        assert.ok(!isNaN(value.valueOf()))
      
          at castDate (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/cast/date.js:13:12)
          at SchemaDate.cast (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/schema/date.js:352:12)
          at SchemaDate.SchemaType.applySetters (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/schematype.js:1179:12)
          at model.$set (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/document.js:1409:20)
          at model.$set (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/document.js:1143:16)
          at model.Document (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/document.js:162:12)
          at model.Model (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/model.js:109:12)
          at new model (/home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/model.js:4833:15)
          at /home/runner/project-exercisetracker-freecodecamp/server.js:62:27
          at /home/runner/project-exercisetracker-freecodecamp/node_modules/mongoose/lib/model.js:5001:18 {
        generatedMessage: true,
        code: 'ERR_ASSERTION',
        actual: false,
        expected: true,
        operator: '=='
      },
      valueType: 'Date'
    }
  },
  _message: 'exercise validation failed'
}

The important bits are the ones about ‘invalid date,’

Thanks for the tip! I didn’t know the validator is accessible like this.

Thank you for the reply! I suppose I managed to pass tests for that route.
Could you look into one more and help me to understand what the test requires?

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

As long as I understand, my response has 5 properties(username, description, duration, date, _id) and 2 properties(username, _id) come from the user object while other 3 properties come from the exercise object.

For the record: in my exercise schema, there is a property which is supposed to be the same with ‘_id’ property of the user object, because I need it for .find method later.

I can’t figure out why I failed the test. What do I miss?

Like I said, it’s the date. From an earlier test:

You can POST to /api/users/:_id/exercises with form data description, duration, and optionally date. If no date is supplied, the current date will be used.

You’re not (were not) handling the no date case, which leads to an invalid date later in the GET tests. Unfortunately, this is not tested in the POST test for exercises.

Did you post any updated code (repl.it preferably since I’m lazy)?

Log:

{
  username: "fcc_test",
  count: 1,
  _id: "5fb5853f734231456ccb3b05",
  log: [{
    description: "test",
    duration: 60,
    date: "Mon Jan 01 1990",
  }]
}

This is what the challenge says should be in the response to GET /api/user/:id/logs

my bad I was looking at the exercise post method

Thank you for reply.
I’m working on the case of a new exercise entry without date input.
Unfortunately I failed to make replit work… so here’s my code snippet.

When a user leave date blank when they submit,
it seems that the date property has ‘’ which led to my else if clause.

The code doesn’t throw any error, it keeps going but nothing but nowhere. The loading circle keeps circling and circling.

 User.findById(id, (err, userData)=>{
      if(err || !userData){
          res.send('Cound not find the user')
      }else if(req.body.date == ''){
          const today = new Date();
          const newExercise = new Exercise({
              userId: id,
              description, // req.body.description
              duration,
              date: today
          })

      }else{
          const newExercise = new Exercise({
              userId: id,
              description, // req.body.description
              duration,
              date: new Date(date) // formatting
          })
          newExercise.save((err,data)=>{
              if(err || !data){
                  res.send('There was an error saving this exercise')
              }else{
                  const {description, duration, date} = data;
                  res.json({
                      username: userData.username,
                      description, // description: description same result
                      duration,
                      date: date.toDateString(),
                      _id: userData.id
                  })
              }
          }) //.save
      } //else
  }) //findById

}) //second post

Ok, I solved the case without date input.
But I’m still failing the same sub test.

app.post('/api/users/:id/exercises', (req,res)=>{
  console.log('req.body', req.body);
  const id = req.params.id;
  const {userId, description, duration, date} = req.body; //object destructuring assignment

  if(req.body.date === ''){
      console.log('here I am')
      let today = new Date()
      console.log(today)
      const newExercise = new Exercise({
          userId: id,
          description, // req.body.description
          duration,
          date: today.toDateString() // formatting
      })
      User.findById(id, (err, userData)=>{
          if(err || !userData){
              res.send('Cound not find the user')
          }else{
              newExercise.save((err,data)=>{
                  if(err || !data){
                      res.send('There was an error saving this exercise')
                  }else{
                      const {userId, description, duration, date} = data;
                      console.log(data.date)
                      res.json({
                          username: userData.username,
                          description, // description: description same result
                          duration,
                          date: date.toDateString(),
                          _id: userId
                      })
                  }
              }) //.save
          } //else
      }) //findById
  }else{
      const newExercise = new Exercise({
          userId: id,
          description, // req.body.description
          duration,
          date: new Date(date) // formatting
      })
      User.findById(id, (err, userData)=>{
          if(err || !userData){
              res.send('Cound not find the user')
          }else{
              newExercise.save((err,data)=>{
                  if(err || !data){
                      res.send('There was an error saving this exercise')
                  }else{
                      const {userId, description, duration, date} = data;
                      res.json({
                          username: userData.username,
                          description, // description: description same result
                          duration,
                          date: date.toDateString(),
                          _id: userId
                      })
                  }
              }) //.save
          } //else
      }) //findById
  }



}) //second post

Alright! good news is I solved this case:

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

bad news is I failed this one this time:

The date property of any object in the log array that is returned from GET /api/users/:id/logs should be a string… Use the dateString format of the Date API.

Even though it seems fine.
I’ve spent 9 hours so far to pass this exercise. Any help will be greatly appreciated!

Here is my replit.
https://replit.com/@samtaitai/boilerplate-project-exercisetracker#server.js

https://boilerplate-project-exercisetracker.samtaitai.repl.co/

The response format looks correct, so you could be hitting the timezone offset error (search the forum for more info). However, you have lots of responses like

req.body {"description":"test","duration":"60"}
{
  username: 'fcc_test_16502541290',
  count: 1,
  _id: new ObjectId("625ce131b4ebeb542d1fffec"),
  log: [ { description: 'test', duration: 60, date: 'Invalid Date' } ]
}

which is likely the problem. You should never have invalid date stored or in the responses when the date just isn’t provided.

This is with your code cloned from your last posted repl.

1 Like

I think I’ve patched that case of undefined.
Could you run my app again and check if it passes?

https://replit.com/@samtaitai/boilerplate-project-exercisetracker#server.js

It still doesn’t on my end. Thanks!