Exercise Tracker date string test

all my test pass except #15 :
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 don’t understand why because I have the same result than the example.

const express = require('express')
const app = express()
const bodyParser = require("body-parser");
const cors = require('cors')
require('dotenv').config()

const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });


const User = require("./model/models.js").UserModel
const Exercice = require("./model/models.js").ExerciceModel

app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});

app.post("/api/users", bodyParser.urlencoded({extended: false}) , (req, res)=>{
  let inputName = req.body["username"] 
  let newUser = new User({username: inputName })
  newUser.save((err,data)=>{
    if (err) return console.log(err);
    res.json({username : data.username , _id: data._id} )
  })
})

app.get("/api/users", (req, res)=>{
  User.find({}, (err , data)=>{
    if (err) return console.log(err);
    res.json(data)
  })
})
app.get("/api/delete", (req, res)=>{
  User.deleteMany({}, (err, data)=>{
    res.json({done: "all user delete"})
  })
})
app.post("/api/users/:_id/exercises", bodyParser.urlencoded({extended: false}) , (req, res)=>{
  let exerciceInfo = new Exercice({
    description: req.body.description,
    duration: parseInt(req.body.duration),
    date: req.body.date 
  })
  let idUser = req.params._id
  if (exerciceInfo.date === ""){
    exerciceInfo.date = new Date().toDateString()
  }else{
    exerciceInfo.date = new Date(exerciceInfo.date).toDateString()
  }
  User.findByIdAndUpdate(idUser,{$push : {log: exerciceInfo}}, {new: true}, (err, data) =>{
    if (err) return console.log(err);
    let responseObject = {
        _id: data.id, 
        username: data.username,
        date: exerciceInfo.date,
        duration: exerciceInfo.duration,
        description: exerciceInfo.description
      };
    res.json(responseObject);
  })
})

app.get("/api/users/:id/logs", bodyParser.urlencoded({extended: false}) , (req, res)=>{
  let from =  Date.parse(req.query.from);
  let to = Date.parse(req.query.to);
  let limit = req.query.limit;
  let maxloop = 0;

    User.findById(req.params.id ,"_id username log" , (err, data)=>{
    if (err) return console.log(err);
    let responceLogObject = [];
    if(data.log.length != 0) {
      if (limit) {
        maxloop = limit;
      }else {
        maxloop = data.log.length;
      }
      let limitIndex = 0;
      for (x in data.log) {
        let dateStr = new Date(data.log[x].date)
        let dateint = Date.parse(dateStr);
        if(from && to){
          if (to > dateint && from < dateint){
            responceLogObject.push({
              description: data.log[x].description,
              duration: data.log[x].duration,
              date: new Date(data.log[x].date).toDateString()
            })
            limitIndex++
          }
        }else if(from == undefined && to){
          if (to > dateint){
            responceLogObject.push({
              description: data.log[x].description,
              duration: data.log[x].duration,
              date: new Date(data.log[x].date).toDateString()
            })
            limitIndex++
          }
        }else if(from && to == undefined){
          if (from < dateint ){
            responceLogObject.push({
              description: data.log[x].description,
              duration: data.log[x].duration,
              date: new Date(data.log[x].date).toDateString()
            })
            limitIndex++
          }
        }else{
          responceLogObject.push({
            description: data.log[x].description,
            duration: data.log[x].duration,
            date: new Date(data.log[x].date).toDateString()
          })
          limitIndex++
        }
        if (limit == limitIndex){
          break
        }
      }
    } 
    responseObject = {
      _id: data.id,
      username: data.username,
      count: data.log.length,
      log: responceLogObject
    }
    res.json(responseObject)
  })
})
const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

model.js file

require('dotenv').config();

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const exerciceSchema = new Schema({
    description:  {type : String, required: true},
    duration: {type : Number, required: true},
    date: { type: String, required: false }
  })

const userSchema = new Schema({
    username : {type : String, required: true},
    log: [exerciceSchema]
})

let exo = mongoose.model("exercice", exerciceSchema);
let user = mongoose.model("user", userSchema);

exports.ExerciceModel = exo
exports.UserModel = user

Replit link :

https://exercisetracker.djoun52.repl.co

Challenge:* Exercise Tracker

Link to the challenge:

I’m having the exact same problem. Any success since writing this? I’ll let you know if I figure anything out.

It’s much harder to debug and answer these type questions without a link to a live project (like on repl.it) because it is much easier to fork a repl than it is to copy/paste chunks of code. That is especially true on this project since the routes are interconnected and an issue in one route can cause issues in another.

So, either post a live project link and maybe someone will be more likely to help. Or if you can’t do that, log all the inputs and all the responses to all the routes and run the tests and make sure that the responses align with the inputs and with the expectations of the tests. There are several logging examples in the forums for all the back end projects.

I actually solved it a minute ago. I didn’t realize you needed to account for the date field in the form being empty when the form is submitted. It looks like the OP has that covered though, so I’m not sure what to say there.

This the link from the exemple site :
https://exercise-tracker.freecodecamp.rocks/api/users/619cf02a1d0f6a058932f7f2/logs

and this is from my personal code :
https://exercisetracker.djoun52.repl.co/api/users/619d0f93bec525a1b88ec86f/logs

I had a similar issue and i think it had something to do with the time zone the Date object used; because at around 23 hours GMT-3 on a sunday the date string would say monday when no date was passed to the form (program has to use current date)

I find the solution, so it comes when you check if the date was blank or not. The value in the test of freecodecamp is not an empty string, but an undefined value
so :

  if (exerciceInfo.date === "" || exerciceInfo.date === undefined ){

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.