Exercise Tracker 14/16 Last Two Won't Pass!

Tell us what’s happening:
My code is working as intended, but last two criteria are not passing. Why?

Your project link(s)
The project is in local.

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

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));

const mongoose = require("mongoose")
mongoose.connect("mongodb+srv://superuser:12345@cluster0.4f2rp.mongodb.net/?retryWrites=true&w=majority")

const User = mongoose.model("User", {
  username: String
})

const Exercise = mongoose.model("Exercise", {
  username: String,
  description: String,
  duration: Number,
  date: String
})

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

app.post("/api/users", (req, res) => {
  new User({username: req.body.username}).save().then(user => {
    res.send({username: user.username, _id: user._id})
  })
})

app.post("/api/users/:_id/exercises", (req, res) => {
  User.findById(req.params._id, function(err, data) {
    if (data != null) {
      new Exercise({
        userid: req.params._id,
        username: data.username,
        date: new Date(req.body.date).toDateString(),
        duration: parseInt(req.body.duration),
        description: req.body.description
      }).save().then(exercise => {
        res.send({_id: req.params._id, username: exercise.username, date: new Date(req.body.date).toDateString(), duration: parseInt(req.body.duration), description: req.body.description})
      })
    }
  });
})

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

app.get("/api/users/:_id/logs?", (req, res) => {
  var from = false;
  var to = false;
  var limit = false; 
  User.findById(req.params._id, function(err, user) {
    Exercise.find({username: user.username}, function(err, exercises) {
      function filter() {
        class Obj {
          constructor(description, duration, date) {
              this.description = description,
              this.duration = duration,
              this.date = date;
          }
        }
        let arr = [];
        if (req.query.limit !== undefined) {
          var intLimit = parseInt(req.query.limit);
        }
        mainLoop: for (let i = 0; i < exercises.length; i++) {
          if (req.query.from !== undefined && req.query.to !== undefined && req.query.limit !== undefined) {
            if ( Date.parse(exercises[i].date) >= Date.parse(new Date(req.query.from).toDateString()) 
            && Date.parse(exercises[i].date) <= Date.parse(new Date(req.query.to).toDateString()) ) {
              from = true;
              to = true;
              limit = true;
              
              if (intLimit <= 1) {
                let object = new Obj(exercises[i].description, exercises[i].duration, exercises[i].date);
                arr.push(object);
                break mainLoop;
              } else if (intLimit > 0) {
                let object = new Obj(exercises[i].description, exercises[i].duration, exercises[i].date);
                arr.push(object);
                intLimit--;
              }
              
            }
          } else if (req.query.from !== undefined && req.query.to !== undefined) {
            if ( Date.parse(exercises[i].date) >= Date.parse(new Date(req.query.from).toDateString()) 
            && Date.parse(exercises[i].date) <= Date.parse(new Date(req.query.to).toDateString()) ) {
              from = true;
              to = true;
              let object = new Obj(exercises[i].description, exercises[i].duration, exercises[i].date);
              arr.push(object);
            }
          } else if (req.query.from !== undefined && req.query.to === undefined) {
            if (Date.parse(new Date(req.query.from).toDateString()) <= Date.parse(exercises[i].date)) {
              from = true;
              let object = new Obj(exercises[i].description, exercises[i].duration, exercises[i].date);
              arr.push(object);
            }
          } else {
            let object = new Obj(exercises[i].description, exercises[i].duration, exercises[i].date);
            arr.push(object);
          }
        }
        return arr;
      }
      let sendObject = {_id: req.params._id, username: exercises[0].username, count: exercises.length, log: filter()};
      if (from === true && to === true && limit === true) {
        let keyValues = Object.entries(sendObject);
        keyValues.splice(2, 0, ["from", new Date(req.query.from).toDateString()], ["to", new Date(req.query.to).toDateString()])
        let newSendObject = Object.fromEntries(keyValues);
        res.send(newSendObject);
      } else if (from === true && to === true) {
        let keyValues = Object.entries(sendObject);
        keyValues.splice(2, 0, ["from", new Date(req.query.from).toDateString()], ["to", new Date(req.query.to).toDateString()])
        let newSendObject = Object.fromEntries(keyValues);
        res.send(newSendObject);
      } else if (from === true && to === false) {
        let keyValues = Object.entries(sendObject);
        keyValues.splice(2, 0, ["from", new Date(req.query.from).toDateString()])
        let newSendObject = Object.fromEntries(keyValues);
        res.send(newSendObject);
      } else {
        res.send(sendObject);
      }
    })
  })
  
})

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 Edg/104.0.1293.63

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

I tried your code, and observed the following:

For the route with query string parameter “limit”, e.g., "/api/users/some_value/logs?limit=2", the API returns incorrect results:
(a) gets all exercise documents - incorrect, (b) counts all documents - incorrect.

Similarly with with query string parameter "to" date.

With the "from" date parameter, (a) gets documents filtered by from date correctly, (b) counts all documents - incorrect.

With these results, the last test will not pass.

EDIT ADD:

Also, with the “from” query parameter the output is showing an additional field, from, for example:

{
    "_id": "6304c90a2d1c044278c4c273",
    "username": "one",
    "from": "Fri Aug 12 2022",        // <===== this should not be there
    "count": 4,
    "log": [
        {
            "description": "d-4",
            "duration": 45,
            "date": "Mon Aug 15 2022"
        }
    ]
}

Thank you my friend :grin:. I have done some changes on it as you said. And the last test is passed, but, this is still not passing: " 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." [15]

I passed all the tests. Sample code for test 15 is:

app.post("/api/users/:_id/exercises", (req, res) => {
// Test 15 Solution - Start
  let userDate = req.body.date;
  if (!userDate) {
    userDate = new Date().toDateString();
  } else {
    userDate = new Date(userDate).toDateString();
  }
// Test 15 Solution - End
// After that, pass the userDate variable to proper sections. That's it!
  User.findById(req.params._id, function(err, data) {
    if (data != null) {
      new Exercise({
        userid: req.params._id,
        username: data.username,
        date: userDate,
        duration: parseInt(req.body.duration),
        description: req.body.description
      }).save().then(exercise => {
        res.send({_id: req.params._id, username: exercise.username, date: userDate, duration: parseInt(req.body.duration), description: req.body.description})
      })
    }
  });
})
1 Like

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