Exercise Tracker (need help fixing)

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

Your code so far

 const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const shortId = require('shortid') 

const cors = require('cors')

const mongoose = require('mongoose')
mongoose.connect(process.env.MLAB_URI, { useNewUrlParser: true, useUnifiedTopology: true })

const exerciseSchema = new mongoose.Schema({
  userId: {type: String, required: true},
  description: {type: String, required: true},
  duration: {type: Number, required: true},
  date: {type: Date, default: Date}
})

const userSchema = new mongoose.Schema({
  _id: {type: String, required: true, default: shortId.generate},
  username: {type: String, required: true},
  exercises: [
    {
      description: String,
      duration: Number,
      date: Date
    }
  ]
})

const User = mongoose.model('User', userSchema)
const Exercise = mongoose.model('Exercise', exerciseSchema)

app.use(cors())

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())


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

// create new user
app.post('/api/exercise/new-user', (req, res) => {
  const username = req.body.username
  User.create({username}, (err, newUser) => {
    res.json({username: newUser.username, _id: newUser._id})
  })
})

// get users
app.get('/api/exercise/users', (req, res) => {
  User.find({}, (err, users) => {
    res.json(users)
  })
})

// add exercise
app.post('/api/exercise/add', (req, res) => {
  let { userId, description, duration, date }  = req.body
  Exercise.create({userId, description, duration: parseInt(duration), date: !date ? undefined : new Date(date)}, (err, exercise) => {
    // console.log(exercise)
    User.findById(exercise.userId, (err, user) => {
      user.exercises.push({description, duration, date: exercise.date})
      user.save()
      console.log(user)
      res.json({username: user.username, _id: exercise.userId, description: exercise.description, duration: exercise.duration, date: exercise.date})
    })
  })
})

// get log
app.get('/api/exercise/log', (req, res) => {
  const id = req.query.userId
  let from = req.query.from
  let to = req.query.to
  let limit = req.query.limit
  
  User.findById(id, (err, user) => {
    Exercise.find({userId: user._id}, (err, log) => {
      from = from !== undefined ? new Date(from) : log.reduce((min, obj) => obj.date < min ? obj.date : min, log[0].date)
      to = to !== undefined ? new Date(to) : undefined
      if (!to) {
        if (limit) {
          log = log.sort((a, b) => a.date.getTime() - b.date.getTime()).slice(0, limit)
          res.json({username: user.username, log: log, count: log.length})
          return
        }
        else {
          to = log.reduce((max, obj) => obj.date > max ? obj.date : max, log[0].date)
        }
      }
      log = log.filter(obj => +obj.date >= +from && +obj.date <= +to)
      res.json({username: user.username, log: log, count: log.length})
    })
  })
})

// Not found middleware
app.use((err, req, res, next) => {
  return next({status: 404, message: 'not found'})
})

// Error Handling middleware
app.use((err, req, res, next) => {
  let errCode, errMessage

  if (err.errors) {
    // mongoose validation error
    errCode = 400 // bad request
    const keys = Object.keys(err.errors)
    // report the first validation error
    errMessage = err.errors[keys[0]].message
  } else {
    // generic or custom error
    errCode = err.status || 500
    errMessage = err.message || 'Internal Server Error'
  }
  res.status(errCode).type('txt')
    .send(errMessage)
})

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

boilerplate-project-exercisetracker-8 - Replit this is the link to my work.

and I promise that in the future this will get more views when people are having challenges with it.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36 Edg/90.0.818.42.

Challenge: Exercise Tracker

Link to the challenge:

This is the same as your other project. Your API endpoints are not named the same as the ones being tested. Fix your endpoints and then console.log() your route inputs and outputs to make sure that you are receiving and sending the correct information.

I passed it. thank you for being my second set of eyes

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