I'm stuck on Exercise Tracker

Story 8th:The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.
Hi, I’m stuck and fail this story for hours and not be able to find the error.
My out put response works find as example:

{"username":"daro","_id":"6167d3edd01e8cbd902a2a05","date":"Thu Oct 14 2021","duration":234,"description":"running"}

my server code is:

const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
const bodyParser = require('body-parser');
const ObjectId= require('mongodb').ObjectId;
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);

const User = mongoose.model('User', new mongoose.Schema({
  username: {type: String, required: true},
  log: Array
}));

const Exercises = mongoose.model('Exercises', new mongoose.Schema({
  description: {type:String, required: true},
  duration: {type:Number, required: true},
  date: String
}));

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

app.post('/api/users', (req,res)=>{
  let newUser = new User({
    username: req.body.username,
    log: []
  });
  newUser.save((err,data)=>{
    if (err) return console.log(err);
    res.json({
      username: data.username,
      _id: data.id
    });
  });
});

app.get('/api/users',(req,res)=>{
  let array=[];
  User.find({},function(err,allUserArray){
    if (err) return console.log(err);
    let returnArray = allUserArray.map(user=>{
      return {username:user.username,_id:user.id};
    })

    res.json(returnArray);
  });
});

function convertDate(date){
  if (date){
    return new Date(date).toDateString();
  } else {
    return new Date().toDateString();
  }
}

app.post('/api/users/:_id/exercises',(req,res)=>{
  User.findById(req.body[':_id'],(err,result)=>{
    if (err) return console.log(err);
    if (result==null){
      res.send("_id Not Found");
    } else {
      new Exercises({
        description: req.body.description,
        duration: parseInt(req.body.duration),
        date: convertDate(req.body.date)
      }).save((err,data)=>{
        if (err) return console.log(err);
        result.log.push(data);
        result.save((err,savedresult)=>{
          if (err) return console.log(err);
        });
        res.json({
          username: result.username,
          _id: result.id,
          date: data.date,
          duration: data.duration,
          description: data.description
        });
      }); 
    }
  });
});

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

Where I deploy: https://quiet-peak-63138.herokuapp.com/
Does anyone know what’s wrong and how to fix it?

Hi @Sereysopea-Ung
Have you tried returning the JSON response like this:

res.json({
   username: result.username,
   description: data.description,
   duration: data.duration,
   date: data.date,
   _id: result.id
})

@theodoreonyejiaku I tried, it’s not work also, dear

@Sereysopea-Ung
I see no reason why you should put the log field in your User schema.

The Exercise schema is better. So create a relationship between them by creating a field called userid in the Exercise schema that will store the _id of a user. With this, you can easily find the exercise logs of a user by using userid as filter.

When this is done, you can do the following:
Once you post a new exercise:
1)Find the user through req.params.id or through request body

2)Save the new Exercise document with userid as req.params.id along with other info such as duration, date, and description.

3)return a json response Like this:

res.json({
   username: user.username, // user found
   description: exercise.description, // exercise saved
   duration: exercise.duration,
   date: exercise.date,
   _id: req.params.id // or user._id or through request body
})

Thanks Theodore, now I will try to do it all over again, I will use your recommendation

I pass this test thanks to @theodoreonyejiaku

Hurrayyyy!!!

Congrats :blush:

1 Like

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