Exercise Tracker Test #8 Username Null or Undefined

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

For the test
The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.
Does not pass because I was unable to return a username.
I tried getting the value by passing in all sorts of things… but maybe I have a really bad approach?
So far, I tried, these.

req.body.username - nope.
req.params.username - nope.
savedUser.username - nope.

I am not sure why all these values are either Null or Undefined…
It’s been 2 days, and I honestly don’t think I can find the reason myself.
Please help me :frowning:

My code is here…

const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
mongoose.set('useFindAndModify', false);
require('dotenv').config()
const bodyParser = require('body-parser')

app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});
let uri = [REDACTED]
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });

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

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

let userSchema = new mongoose.Schema({
  username:{type: String, required:true},
  log: [exerciseSchema]
})

let Session = mongoose.model('Session', exerciseSchema)
let User = mongoose.model('User', userSchema)

app.post('/api/users', bodyParser.urlencoded({extended: false}), (req, res)=>{
  let newUser = new User({username: req.body.username})
  newUser.save((error, savedUser)=>{
    if(!error){
      let resObj = {}
      resObj['username'] = savedUser.username
      resObj['_id'] = savedUser.id
      res.json(resObj)
    }
  })
  //res.json({})
})

app.get('/api/users', (req,res)=>{
  User.find({},(error, arrayOfUsers)=>{
    if(!error){
      res.json(arrayOfUsers)
    }
  })
})


app.post('/api/users/:_id/exercises', bodyParser.urlencoded({extended: false}) ,(req,res)=>{

  let newSession = new Session({
    description: req.body.description,
    duration: parseInt(req.body.duration),
    date: req.body.date
  })

  if(newSession.date === ''){
    newSession.date = new Date().toISOString().substring(0, 10)
  }

  User.findByIdAndUpdate(
    req.body._id,
    {$push: {log : newSession}},
    {new: true},
    (error, updatedUser)=>{
      if(!error){
        let resObj = {}
        resObj['username'] = req.body.username
        resObj['description'] = newSession.description
        resObj['duration'] = newSession.duration
        resObj['date'] = new Date(newSession.date).toDateString()        
        resObj['_id'] = req.body._id
        res.json(resObj)
      }
    }
  )
})

app.get

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

Challenge: Exercise Tracker

Link to the challenge:

If the problem is here

then you need to use the username returned in the callback data in updatedUser. The user name is not part of the information provided to this route (according to the spec), so req.body.username should be null.

Without a live project link (repl.it perhaps), it’s hard to debug exactly. You really need to log your route inputs and responses like you can find in many other threads about problems with back end projects if the above doesn’t fix your problem.

1 Like

I did find a way around this, I used req.params._id instead of req.body._id on User.findByIdAndUpdate.
I need to still dig in more to study why my understanding is bad in this section.

Thank you for your reply though, that adds more to my understanding :pray:

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