Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:

I cannot get “8. The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.” to work, I have tried everything.

###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/131.0.0.0 Safari/537.36

Challenge Information:

Back End Development and APIs Projects - Exercise Tracker

you will need to share your code for people to be able to help you

const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
const mongoose = require('mongoose')
app.use(cors())
app.use(express.static('public'))
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});
}




const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true});
const personSchema = new mongoose.Schema({
  username:{
    type: String, required: true, unique: true
  },
  count:{
    type: Number, default: 0
  },
 log:[{
    
      description: {type: String, required: true},
      duration: {type: Number, required: true},
      date: {type: String, required: true}
    
  }]
});

const Person = mongoose.model("Person", personSchema);
  app.post("/api/users", async (req, res)=>{
    try{
    let name  = req.body;
    const testPerson = new Person({
    username:name.username
  });

 

  const savedPerson= await testPerson.save();
  res.json({username : savedPerson.username, _id : savedPerson._id})
} catch(err){
  return console.error(err);
}
  })

  app.get("/api/users", async (req, res)=>{
    try{
      const users = await Person.find({});
      res.json(users.map((user)=>({
      username: user.username,
      _id: user._id.toString(),
      })))
    } catch(err){
      console.error(err)
    }
  })
  app.post("/api/users/:_id/exercises", async (req, res)=>{
    try{
    const { _id } = req.params;
    const { description, duration, date } = req.body;
    let selectedPerson = await Person.findById(_id)
    const exercise = {
      description,
      duration: parseInt(duration),
      date: date ? (new Date(date)).toDateString() : (new Date()).toDateString(),
    };

    
    selectedPerson.log.push(exercise);
    selectedPerson.count = selectedPerson.log.length;
    await selectedPerson.save();
    console.log({
      username: selectedPerson.username, // Return the user's username
      description: exercise.description,
      duration: exercise.duration, // Return the duration of the exercise
      date: exercise.date, // Return the date of the exercise
      _id: selectedPerson._id, // Return the user's _id
      })

      //HERE IS WHERE THE ISSUE  IS FOR #8

    res.json({
  
      username: selectedPerson.username, // Return the user's username
      description: exercise.description.toString(),
      duration: parseInt(exercise.duration), // Return the duration of the exercise
      date: new Date(exercise.date).toDateString(), // Return the date of the exercise
      _id: selectedPerson._id.toString(), // Return the user's _id
      });
    } catch(err){
      return console.error(err);
    }
  })
  app.get(("/api/users/:_id/logs"), async (req, res)=>{
    
    const {from, to, limit} = req.query;
    try{
    const selectedPerson = await Person.findById(req.params._id);
    if(from){
      selectedPerson.log = selectedPerson.log.filter((exercise)=>
       new Date(exercise.date)  >= new Date(from)
      )
    }
    if(to){
      selectedPerson.log = selectedPerson.log.filter((exercise)=>
    new Date(exercise.date) <= new Date(to)
    )
    }
    if(limit){
      selectedPerson.log = selectedPerson.log.slice(0 ,limit);
      
    }

    res.json({
      _id: selectedPerson._id.toString(),
      username: selectedPerson.username,
      count: selectedPerson.count,
      log: selectedPerson.log.map((exercise)=>({
    
        description: exercise.description,
        duration: exercise.duration,
        date: exercise.date}
      ))
    })
  }
  catch{
    if(err) return console.error(err);
  }
  });

Sorry could not add code until the post was approved.

You have a syntax error in the code (extra }).


Anyway, remove unique: true from the username in your personSchema and delete your collection on MongoDB Atlas. Then try it again, you should pass now, at least I do with your code and my own DB.

1 Like

I removed unique: true, but I do not see any extra brackets. I deleted the collection and still have no luck.

Could deleting the old database entirely and creating a new one help?

Did you try?

As I said, your code was passing for me after I updated the schema and used a fresh collection. You should have been getting an error about unique values using the previous schema.

Yes I updated the schema and deleted and recreated the database, however my code is still failing. Now test 15 also fails, however I agree that my code does the required actions. Could it be my browser or OS? I tried the tests on brave and chrome on my mac with no luck. Where were you seeing the unique errors? Thanks again for your responses.

Here is a preview from the web console

{_id: "675794c47148e505802201f2", username: "fcc_test_17337929641", count: 1,…}
count: 1
log: [{description: "test", duration: 60, date: "Mon Dec 09 2024"}]
0: {description: "test", duration: 60, date: "Mon Dec 09 2024"}
username: "fcc_test_17337929641"
_id: "675794c47148e505802201f2"

Could be an issue with the date. Make sure your system clock is correct.

Some people have better luck using Gitpod, Replit, or Glitch with date related issues when running locally.

1 Like

Yes this was the issue, my code worked perfectly on Gitpod. How frustrating! Thank you for all your help + efforts, I really appreciate it! :slight_smile: