Exercise Tracker - dateString format

Hello guys, I’m having troubles with this project. I think I’m done but I keep getting the same error, before you say “read the error”, I have already read the error, and I think my code provides the right answer.

Here is my code (It’s quite messy):

const express = require('express');
const app = express();

const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const cors = require('cors');
require('dotenv').config();

mongoose.connect(process.env.MONGOURI);

const userSchema = new mongoose.Schema({
  username: String
}), User = mongoose.model('User', userSchema);

const exerciseSchema = new mongoose.Schema({
  username: String,
  description: String,
  duration: Number,
  date: Date
}), Exercise = mongoose.model('Exercise', exerciseSchema);

const logSchema = new mongoose.Schema({
  username: String,
  count: Number,
  log: [Object]
}), Log = mongoose.model('Log', logSchema);

app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});
/*
app.use('/', (req, res, next)=>{
  console.log(req.method, req.originalUrl);
  next();
})
*/
app.get('/api/users', (req, res)=>{
  User.find((err, data)=>{
    if (err) return res.json(err);

    res.json(data);
  })
})

app.post('/api/users', bodyParser.urlencoded({
  extended: false
}), (req, res)=>{
  const username = req.body.username;
  
  User.findOne({username: username}, (err, data)=>{
    if (err) return res.json(err);

    if (data){
      res.json(data);
    } else {
      const user = new User({username: username});
      user.save((err, data)=>{
        if (err) return res.json(err);

        res.json({
          username: data.username,
          _id: data._id
        });
      })

      const log = new Log({
        username: username,
        count: 0,
        log: []
      })

      log.save();
    }
  })
});

app.post('/api/users/:_id/exercises', bodyParser.urlencoded({
  extended: false
}), (req, res)=>{
  const id = req.params["_id"];

  User.findById(id, (err, data)=>{
    if (err) return res.json(err);

    if (data){
      const {
        description, duration, date
      } = req.body;

      const user = data;
      const dateFormatted = 
      date ? new Date(date) : new Date();

      if (dateFormatted == "Invalid Date") {
        return res.json({
          error: dateFormatted
        });
      }

      const exercise = new Exercise({
        username: user.username,
        description: description,
        duration: duration,
        date: dateFormatted
      })

      exercise.save((err, data)=>{
        if (err) res.json(err);

        const response = {
          username: user.username,
          description: data.description,
          duration: data.duration,
          date: data.date.toDateString(),
          _id: user._id
        }

        res.json(response);
      })

      Log.find({
        username: user.username
      }).exec((err, data)=>{
        if (err) return;

        const document = data[0];

        document.count++;
        document.log.push({
          description: exercise.description,
          duration: exercise.duration,
          date: exercise.date.toDateString()
        });

        document.save((err, data)=>{
          if (err) return console.log(err);
        })
      });

    } else {
      res.json({
        error: "User not found"
      })
    }
  })
})

app.get('/api/users/:_id/logs', (req, res)=>{
  const id = req.params._id;

  User.findById(id, (err, data)=>{
    if (err) return res.json(err);

    if (data){
      const username = data.username;

      Log.find({
        username: username
      }, (err, data)=>{
        if (err) return res.json(err)

        let logs = data[0].log;

        if (req.query.from){
          let fromDate = new Date(req.query.from);
          fromDate = fromDate.getTime();

          logs = logs.filter(ex=>{
            let date = new Date(ex.date);
            date = date.getTime();

            return date >= fromDate;
          })
        }

        if (req.query.to){
          let toDate = new Date(req.query.to);
          toDate = toDate.getTime();

          logs = logs.filter(ex=>{
            let date = new Date(ex.date);
            date = date.getTime();

            return date <= toDate;
          })
        }

        if (req.query.limit){
          const limit = req.query.limit;
          logs = logs.slice(0, limit);
        }

        const response = {
          username: username,
          count: logs.length,
          _id: data[0]._id,
          log: logs
        }

        res.json(response);
        
        console.log(req.originalUrl);
        console.log(response);
      });
    } else {
      res.json({
        error: "User not found"
      });
    }
  })
})

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

Here’s the error I keep getting:

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.

I debugged a little bit, and this is what my code was supposed to answer:

image

And my code sent this:

image

I don’t know how to solve this, because my code takes the date directly from the input, and with other cases it works. Any help please?

I didn’t sleep well last night. But today I woke up and realize that it’s just a freecodecamp’s issue and I’m gonna expain that.

First of all one of the test cases are with the empty field “date” that needs to be the actual date. So due to the replit server being in another country, the time on the replite server was on Sat Dec 11 2021 while on my local computer still was the day before.

So freecodecamp grabs the day of my local computer and do the test cases in base of that. Then I tried with the EXACTLY SAME CODE today, and this is the result:

I’m going to open an issue on github because other people can have the same problem as me.

1 Like

There’s many posts already in the forums about this issue. You’re probably seeing a timezone offset issue since the repl.it servers are running in UTC and your browser is running in whatever time you have it configured.

Since your problem appears to be transient, try the program tests right before midnight UTC in your time (that’s 6 PM CST for me) and right after. At least one run should pass. You can do the same thing at midnight local time. This is probably what you are seeing.

You can also check your timezone configuration. Repl.it will be in UTC and your system should have the correct time and timezone for both the system time and the localized time seen by the user (my system is UTC and localized to US Central time and the times are correct). Since the tests for the project are run in your browser, your system time must be correct for them to work.

Finally, check to see if this has been solved recently before filing an issue. I was having this problem on this project back in September (tests failed between 7 PM and midnight local when the dates were different) but I haven’t tested it recently. There’s ambiguity in the spec that makes these tests difficult since only the date is being stored and it’s not clear to the tests whether the user’s date or the server’s date is correct since a date string doesn’t indicate timezone.

1 Like

You’re right. But you need to understand that the error message can lead to get things worse.

I would prefer if in the content of the project specs says something about this to prevent me to spend a lot of time trying to figure out what I need to fix.

It would be even BETTER if the project requires the unix timestamp instead of requiring the string. In a real project it must be like that, so there is no confusion between the server and the client.

1 Like

Even I ended up in the same situation. I tried running the tests an hour prior to midnight & this test case was passing fine as I was in the same day as UTC.
Later, I spent some time fixing other test case & till the time I managed to fix other test case, I was past midnight, meaning I was in next day while replit servers in previous day.

I started wondering how did this test case which was passing some time back is failing now :thinking:. I went through the code couple of times, tried testing it locally, but didn’t find any issues. :confused:

Finally decided to search “Use the dateString format of the Date API” which was written in this test case, and ended up on this post on the forum.
Only to realise the real problem was timezone difference between my system & replit servers :astonished:

For anyone, who has same issue with this test case, the solution that worked for me was that to just change the timezone of your system to UTC for the time till the test cases are running & submitted.
The test cases will pass & solution will be accepted.