Problem with passing tests (Exercise Tracker)

Hello! I have difficulty passing tests 9-15, when compairing return from https://exercise-tracker.freecodecamp.rocks/ mine is the same, I’ve tryed looking at the console output as was suggested in this forum post, but i do not see any problem, would appreciate any help, thanks in advance

Replit project link

Code what i have written:

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();


const port = process.env.PORT || 3000;

app.use(cors())
app.use(express.static('public'))

const bodyParser = require("body-parser");

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


const mongoose = require('mongoose');

mongoose.set('strictQuery', true);

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });

var urlencodedParser = bodyParser.urlencoded({ extended: false })

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  }
})

let userModel = mongoose.model("userModel", userSchema);

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

let exerciseModel = mongoose.model("exerciseModel", exerciseSchema);

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

app.post('/api/users',(req,res)=>{
  console.log(req.body)
  let username = req.body.username;
  if(username == '' || username === undefined){
    return res.json({error: "username must be provided"})
  }

  userModel.findOne({username: username}, function(err,data){
    if(!err && data == null){
      let newUser = new userModel({username:username})
      
      newUser.save(function (err,response){
        
        if(!err){
          let savedusername = response.username;
          let savedid = response['_id']
          
          return res.json({username: savedusername, _id: savedid })
        }
        
      })
    }
    else{
      return res.json({data})
    }
  })
})

app.get('/api/users', function (req, res) {
	userModel.find({}, function (err, data) {
		if (!err) {
			return res.json(data);
		}
	});
});

app.post('/api/users/:_id/exercises', (request, response) => {
  let input = request.params.input
  let id = request.params['_id']
  console.log('params', request.params)
  console.log('id', id)
  
  
  let description = request.body['description']
  let duration = request.body['duration']
  let input_date = request.body['date']
  let username;

  let date;
  let checkdate = new Date(Date.parse(input_date)).toUTCString();


  if(input_date == ''){
    date = Date.now();
    date = new Date(date).toUTCString();
  }
	else if (isNaN(duration)) {
		return res.json({ error: 'duration is not a number' });
	}
  else if(checkdate === 'Invalid Date' && input_date != ''){
    return response.json('Invalid Date')
  }
  else{
    date = checkdate;
  }
  
  userModel.findOne({_id: id}, (error, result) => {
    //console.log(result)
    if(!error && result != undefined){
      
      username = result.username;
      console.log(username)

      let newExercise = new exerciseModel({
        userId: id,
        date: date,
        duration: duration,
        description: description
      })
      
        newExercise.save(function (err,res){
        
        if(!err){          
                return response.json({
                  username: username,
                  description: description,
                  duration: parseInt(duration),
                  date: new Date(date).toDateString(),
                  _id: id,
                })
        }
      
        })
      
    }else{
      response.json('URL not Found')
    }
    
  })
  
})



app.all('/api/users/:_id/logs', function (req, res) {
  let id = req.params['_id'];

  
	userModel.findById(id, function (err, data) {
    let username = '';
    if(data === undefined){
      return res.json({error: "wrong user id"})
    }
    else{
      username = data.username;
    }
    if(!err && username != ''){      
        exerciseModel.find({userId: id}).sort({date: 'asc'}).exec(function (error, exercises) { 
        
        if(!error){
           return res.json({
              _id: id,
              username: username,
              count: exercises.length,
              log: exercises.map(function (e){
                        return{
                              description: e.description,
                              duration: parseInt(e.duration),
                              date: new Date(e.date).toDateString()
                        }
                  })
             
            });
        }

	     });
      
    }
	});
});


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


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

Your log array is empty (so count is also always 0)

Request URL: https://boilerplate-project-exercisetracker.terrachad.repl.co/api/users/6442e10c102c47d65caef23f/logs

{"_id":"6442e10f102c47d65caef24e","username":"fcc_test_16821045912","count":0,"log":[]}

Yeah, but what should i return instead if there is no exercise assigned to that user?

How excatly are you checking the responses?


All of the /api/users/:_id/exercises that do not have a date in the payload are returning "Invalid Date"

if (input_date == '')

Are you sure that is what input_date will be when the date on body is not supplied?


You do not have any logic for the last test(s).

1 Like

Thanks, you was wright, i haven’t even thought about body req, i’ve rethinked and changed date validation to look if it’s exists or it is an empty string and every test passed

If anyone will have the same problem, here is working solution for checking the date in /exercises:

let input = request.params.input
let id = request.params['_id']
console.log('params', request.params)
console.log('id', id)
  
let username;
let date;
  
let description = request.body['description']
let duration = request.body['duration']
let input_date = request.body['date']
let checkdate = new Date(Date.parse(input_date)).toUTCString();

if(request.body['date'] === '' || !('date' in request.body)){
    date = Date.now();
    date = new Date(date).toUTCString();
    console.log('no date is provided')
  }
  else if(checkdate === 'Invalid Date' && request.body['date'] === ''){
    return response.json('Invalid Date')
  }
  else if (isNaN(duration)) {
    console.log('isNaN(duration)')
		return res.json({ error: 'duration is not a number' });
    
	}
  else{
    date = checkdate
    
  }

Glad you got it. I have blurred your code to avoid spoilers.

1 Like