Exercise Tracker: Can't pass last test

I can’t seem to pass the last test " You can add from , to and limit parameters to a GET /api/users/:_id/logs request to retrieve part of the log of any user. from and to are dates in yyyy-mm-dd format. limit is an integer of how many logs to send back."

I have looked at the other forums for this issue and still wasn’t able to resolve it. Any help would be appreciated.

project: project

const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()

var bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.connect("mongodb+srv://user_1:Rs5t6w@cluster0.cbpzj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority",{useNewUrlParser: true, useUnifiedTopology: true});

var db = mongoose.connection;

app.use(express.urlencoded({extended: true}));

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


mongoose.set('useFindAndModify', false)


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


const Schema = mongoose.Schema;
const userSchema = new Schema({
  username: {
    type: String,
    required: true},
  count: Number,
  log: [{
    description: String,
    duration: Number,
    date: {type: String, required: false},
    _id: false
  }]
});

const User = mongoose.model("User", userSchema);

app.post("/api/users", (req,res)=>{
    var user = new User({
      username: req.body.username
    });
  user.save(function(err,data){
    if(err) return console.error(err);
    res.send({
      username: data.username,
      _id: data._id
    })
  })
});

app.get("/api/users", (req,res)=>{
    User.find({}, function(err,list){
      if(err){
        console.log(err)
      }
      else{
        res.send(list)
      }
    })
});

const dateValidation = (input) =>{
  if(input === undefined){
    return new Date().toDateString()
  }
  else {
    return new Date(input).toDateString()
  }
};

app.post("/api/users/:_id/exercises", (req,res)=>{
 let exercise = {
        description: req.body.description,
       duration: parseInt(req.body.duration),
       date: dateValidation(req.body.date)
      };
  User.findOneAndUpdate ({_id: req.params._id}, exercise, {new: true}, (err,data)=>{
    if(err){
      res.send({
        error: err
      })
    }  
    else{
    data.log.push(exercise);
      console.log("saving exercise")
      data.save();
      res.send({
        username: data.username,
        _id: req.params._id,
        description: exercise.description,
        duration: exercise.duration,
        date: exercise.date
    })
    }})
});
  
app.get("/api/users/:_id/logs?", (req,res)=>{
   User.findById(req.params._id, (err,data)=>{
      let dataset = data.log;
     if (err) {res.send ({error: err}) }
     else{
     if(req.query.from && req.query.to){
        dataset = data.log.filter((item)=>{
          new Date(item.date) >= new Date(req.query.from) && new Date(item.date) <= new Date(req.query.to)
        })
       
      }
      if(req.query.limit){
        dataset =data.log.filter((d,i)=> i < req.query.limit )
        
      }
     
        res.send({
        _id: data._id,
      username: data.username,
      from: new Date(req.query.from).toDateString(),
      to: new Date(req.query.to).toDateString(),
      count: dataset.length,
        log: dataset
        })
    
      } 
     })
    });



I figured it out after creating tests for every possible scenario and logging the req.query items to the log so I could see what was being tested.

There were two issues:

dataset = data.log.filter((item)=>{
          new Date(item.date) >= new Date(req.query.from) && new Date(item.date) <= new Date(req.query.to)
        })

the above code needed the bracket removed or the result returned. Silly mistake.

the next issue was that my comparison of dates wasn’t valid and I needed to change the code to this:

if(req.query.from){
        dataset = data.log.filter((item)=>
          new Date(item.date).getTime() >= new Date(req.query.from).getTime() && new Date(item.date).getTime() <= new Date(req.query.to).getTime()
        )
       

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