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
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: