Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:
Describe your issue in detail here.

I am unable to pass this test.

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.

This is what the test output gives:

// running tests
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.
// tests completed

Here is my code

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

// mongoose.connect(process.env['MONGO_URI'], { useNewUrlParser: true, useUnifiedTopology: true });

// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(bodyParser.json());

// const Schema = mongoose.Schema;

// const userSchema = new Schema({
//   username: String
// });

// const exerciseSchema = new Schema({
//   username: String,
//   description: String,
//   duration: Number,
//   date: Date,
//   sepid: String
// });

// let Exercise =  mongoose.model("Exercise", exerciseSchema);

// let User = mongoose.model("Url", userSchema);

// app.use(cors())

// app.use(express.static('public'))

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


// app.post("/api/users", function(req, res){
//   console.log(req.body)
//   User.findOne({username: req.body.username}, (err, data) => {
//     if (!data){
//       let user = new User({username: req.body.username})
//       user.save((err, data) => {
//         res.json({username: data.username, _id: data.id})
//         if (err) return console.error(err); 
//       })
//     }
//     else{
//       res.json({username: data.username, _id: data.id})
//     }
//     if (err) return console.error(err); 
//   })
  
// })

// // Fix if user alreadys exists return the user id instead of a new one

// app.post("/api/users/:_id/exercises", (req, res) => {
//   let id = req.params._id;
//   console.log(id)
//   console.log(typeof id)
//   User.findOne({sepid: id}, (err, data) => {
//     if(!data){
//       res.json({_id : "Invalid ID"})
//     }
//     else{
//       thedate = new Date(req.body.date);
//       exercisejson = {username: data.username,
//       description: req.body.description,
//       duration: req.body.duration,
//       date: thedate, sepid: id};

//       exerciseoutput = {username: data.username,
//       description: req.body.description,
//       duration: parseInt(req.body.duration),
//       date: thedate.toDateString(), _id: id};
      
//       let exercise = new Exercise(exercisejson)
//       exercise.save((err, data) => {
//         res.json(exerciseoutput)
//         if (err) return console.error(err); 
//       }) 
//     }
//     if (err) return console.error(err);    
//   })
  
// })

// app.get("/api/users", (req, res) => {
//   User.find({}, (err, data) => {
//     fixeddata = []
//     data.forEach(function(item){
//       fixeddata.push({username: item.username, _id: item._id})
//     });
//     console.log(fixeddata)
//     res.json(fixeddata)
//     if (err) return console.error(err); 
//   })
// })


// app.get("/api/users/:_id/logs", (req, res) => {
//   id = req.params._id
//   Exercise.find({sepid: id}, (err, data) =>{
//     console.log(data)
//     console.log(typeof data)
//     if(data.length == 0){
//       res.json({_id: "Invalid ID"})
//     }
//     else{
//       logs = []
//     data.forEach(function(item){
//       logs.push({description: item.description, duration: item.duration, date:           item.date.toDateString()})
//     });
//     // console.log(logs)
//     res.json({username: data[0].username,
//               count: logs.length,
//               _id: id,
//               log: logs
//              })
//     }
//     if (err) return console.error(err); 
//   })
// }) 

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


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


mongoose.connect(process.env['MONGO_URI'], { useNewUrlParser: true, useUnifiedTopology: true });

const { Schema } = mongoose;

const ExerciseSchema = new Schema({
  userId: { type: String, required: true },
  description: String,
  duration: Number,
  date: Date,
});
const UserSchema = new Schema({
  username: String,
});
const User = mongoose.model("User", UserSchema);
const Exercise = mongoose.model("Exercise", ExerciseSchema);


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


app.post("/api/users", (req, res) => {
  // console.log(`req.body`, req.body)
  const newUser = new User({
    username: req.body.username
  })
  newUser.save((err, data) => {
    if(err || !data){
      res.send("There was an error saving the user")
    }else{
      res.json(data)
    }
  })
})

// if(req.body.date == ""){
  //   date = new Date()
  // }
  // else{
  //   date = new Date(req.body.date)
  // }

app.post("/api/users/:id/exercises", (req, res) => {
  const id = req.params.id
  const {description, duration, date} = req.body
  User.findById(id, (err, userData) => {
    if(err || !userData) {
      res.send("Could not find user");
    }else{
      console.log(new Date().toString())
      // let inputdate = new Date()
      // if(!(date == "")) inputdate = new Date(date);
      let inputdate = req.body.date ? new Date(req.body.date).toDateString() : new Date().toDateString();
      const newExercise = new Exercise({
        userId: id, 
        description,
        duration,
        date: inputdate, 
      })
      newExercise.save((err, data) => {
        if(err || !data) {
          res.send("There was an error saving this exercise")
        }else {
          const { description, duration, date, _id} = data;
          res.json({
            username: userData.username,
            description,
            duration,
            date: date.toDateString(),
            _id: userData.id
          })
        }
      })
    }
  })
})

app.get("/api/users/:id/logs", (req, res) => {
  const { from, to, limit } = req.query;
  const {id} = req.params;
  User.findById(id, (err, userData) => {
    if(err || !userData) {
      res.send("Could not find user");
    }else{
      let dateObj = {}
      if(from){
        dateObj["$gte"] = new Date(from)
      }
      if(to){
        dateObj["$lte"] = new Date(to)
      }
      let filter = {
        userId: id
      }
      if(from || to ){
        filter.date = dateObj
      }
      let nonNullLimit = limit ?? 500
      Exercise.find(filter).limit(+nonNullLimit).exec((err, data) => {
        if(err || !data){
          res.json([])
        }else{
          const count = data.length
          const rawLog = data
          const {username, _id} = userData;
          const log= rawLog.map((l) => ({
            description: l.description,
            duration: l.duration,
            date: l.date.toDateString()
          }))
          res.json({username, count, _id, log})
        }
      })
    } 
  })
})

app.get("/api/users", (req, res) => {
  User.find({}, (err, data) => {
    if(!data){
      res.send("No users")
    }else{
      res.json(data)
    }
  })
})





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


Your project link(s)

solution: boilerplate-project-exercisetracker - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

Currently works for me. You probably are experiencing the time zone offset problem as explained in other posts in the forums.