Exercise tracker - The response returned from `POST /api/users/:_id/exercises` will be the user object with the exercise fields added

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

I’m currently working on the exercise tracker challenge and my code is stuck on

“The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.”

It’s passing all the others except this one.

const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config();
const mongoose = require("mongoose");

mongoose.connect(process.env.MONGO_URI).catch((err) => console.log(err));

mongoose.connection.on("error", (err) => {
  console.log("Mongoose connection error: " + err);
});

let userSchema = mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
    }
  },
  { versionKey: false }
);

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

let exerciseSchema = mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
    duration: {
      type: Number,
      required: true,
    },
    date: String,
    userId: {
      type: String,
      required: true,
    },
  },
  { versionKey: false }
);

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


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

app.post("/api/users", async (req, res) => {
  let username = req.body.username;
  let existingUser = await User.findOne({ username })
  
  if (username === ""){
    res.json({error: "username is required"})
  }

  if (existingUser){
    return res.json(existingUser)
  }
   
  let user = await User.create({
    username
  })

  res.json(user)
});

app.get("/api/users", async (req, res) => {
  let usersList = await User.find();
  res.json(usersList);
});


app.post("/api/users/:_id/exercises", async (req, res) => {
  let userId = req.params._id;
  let description = req.body.description;
  let duration = parseInt(req.body.duration);
  let date = new Date(req.body.date);

  if (date == "Invalid Date"){
    date = new Date().toDateString()
  } else {
    date = new Date(date).toDateString()
  }

  if (description === ""){
    return res.json({error: "description is required"})
  }

  if (duration === ""){
    return res.json({error: "duration is required"})
  } 
  
  let user = await User.findById(userId).select("username")

  if (!user){
    return res.json({error: "unknown userId"})
  } 

  let exercise = await Exercise.create({
    username: user.username,
    description, 
    duration, 
    date,
    userId,
  });

  return res.json({
    _id: user._id,
    username: user.username,
    date,
    duration,
    description,
  });
});


app.get("/api/users/:_id/logs", async (req, res) => {
  let userId = req.params._id;
  let user = await User.findById(userId).select("username")
  let count = await Exercise.countDocuments({userId})
  let log = await Exercise.find({userId})

  if (!user){
    return res.json({error: "unknown userId"})
  }
  
  if (req.query.from || req.query.to){
    let from = new Date(req.query.from);
    let to = new Date(req.query.to);
    let limit = parseInt(req.query.limit);
    
    if (from == "Invalid Date"){
      from = new Date(0)
    } else {
      from = new Date(from)
    }
    
    if (to == "Invalid Date"){
      to = new Date()
    } else {
      to = new Date(to)
    }

    log = await Exercise.find({userId, date: {$gte: from, $lte: to}}).limit(limit)
    count = log.length
  } else if (req.query.limit){
    let limit = parseInt(req.query.limit);
    log = await Exercise.find({userId}).limit(limit)
    count = log.length
  }
  

  res.json({
    _id: user._id,
    username: user.username,
    count,
    log
  });
});

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

Your project link(s)

solution: http://localhost:3000

Your browser information:

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

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

1 Like

I’m having the same issue. Maybe we could find someone who had this issue and fixed it. Their code may have some hints as to what to do differently.

I just put my code onto replit. Now that test passes but the last test ( from , to and limit parameters to a GET /api/users/:_id/logs) doesn’t pass.

If you were doing the project locally you can try putting it on replit or glitch and see if that does anything.

2 Likes

I’ll give it a shot. Thank you for the advise!

You need to log your route inputs and responses from the affected route at least (better all of them, with the route name) to track what the code is actually doing. I didn’t test it since you didn’t post a repl (you posted a link to localhost, which is my computer here) but my guess is your return JSON has incorrect values, incorrect formats, or incorrect types.

Check everything by logging and if you are still stuck, post a repl with your progress.

https://replit.com/join/rpyhzyslxp-nafis3000

https://boilerplate-project-exercisetracker.nafis3000.repl.co/

The issue I’m having now is that the from, to and limit query isn’t working. The issue I originally posted about was fixed when I put my code on replit for some reason.

I have no idea either.
Locally, mine passed all tests but this one.
Then, I tried from Replit… et voila! (Finally worked)

I had the same issue with “The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.” and looking at your code I could resolve it - I had missed parseInt on the duration. Thanks!

I was able to pass all the test excpet this one: Test 15: Failed: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.

Still having this test pending.

I had same problem; I guess is the date, check the UTC

link: Back End Development and APIs Projects - Exercise Tracker

thank you for the solution

when you return the object in res.json make sure the duration value should be in number

return res.json(
{
username : user.username ,
description ,
duration : Number(duration),
date : date.toDateString() ,
_id ,
});