FCC - Exercise Tracker cannot pass on test 7 and 8 please help

Tell us what’s happening:
When I ran the test, I cant pass on test 7 and test 8.

Test 7:
You can POST to /api/users/:_id/exercises with form data description , duration , and optionally date . If no date is supplied, the current date will be used.

Test 8:
The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.

the desired result is showing when I fill out the form manually but when I run the test, it always fails saying : TypeError: Cannot read property ‘username’ of null.

I am encountering this error when I run the test: (error attached).

throw er; // Unhandled ‘error’ event
^

TypeError: Cannot read property ‘username’ of null
at /home/runner/boilerplate-project-exercisetracker/server.js:105:50
at /home/runner/boilerplate-project-exercisetracker/node_modules/mongoose/lib/model.js:5074:18
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted ‘error’ event on Function instance at:
at /home/runner/boilerplate-project-exercisetracker/node_modules/mongoose/lib/model.js:5076:15
at processTicksAndRejections (internal/process/task_queues.js:79:11)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fcc-exercise-tracker@0.1.0 start: node server.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fcc-exercise-tracker@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/runner/.npm/_logs/2021-12-19T23_55_40_468Z-debug.log
exit status 1

The issue/error is specifically happening in the response.json object. I attached the screenshots of the server.js code.




Your project link(s)

Exercise Tracker file: https://replit.com/@Luderio/boilerplate-project-exercisetracker#.replit

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0

Challenge: Exercise Tracker

Link to the challenge:
https://boilerplate-project-exercisetracker.luderio.repl.co
`const express = require(‘express’)
const app = express()
const cors = require(‘cors’)
require(‘dotenv’).config()
const bodyParser = require(‘body-parser’);
const mongoose = require(‘mongoose’);

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

//DATABASE SETUP.
const mySecret = process.env[‘MONGO_URI’];
mongoose.connect(mySecret);

//SCHEMA.
const excerciseLogSchema = mongoose.Schema({
“description”: {“type”: String, “required”: true},
“duration”: {“type”: Number, “required”: true},
“date”: String
});

const userRecordSchema = mongoose.Schema({
“username”: {“type”: String, “required”: true},
“log”: [excerciseLogSchema]
});

//MODEL.
const SessionLogs = mongoose.model(“SessionLogs”, excerciseLogSchema);

const UserRecords = mongoose.model(“UserRecords”, userRecordSchema);

//BODY PARSER.
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//API ENDPOINT(1) - POST / api/users (collecting the username and creating a new database records).
const apiUserPathPOST = ‘/api/users’;

app.post(apiUserPathPOST, (request, response) => {
const userName = request.body.username;

const newUser = new UserRecords({“username”: userName});
newUser.save((error, userData) => {
if (error) return console.log(error);
response.json({
“username”: userData.username,
“_id”: userData.id
});
});
});

//API ENDPOINT(2) - GET requests to /api/users returns an array.
const apiUserPathGET = ‘/api/users’;
app.get(apiUserPathGET, (request, response) => {
UserRecords.find({}, (error, users) =>{
if (error) {
console.log(error);
response.send(“Something went Wrong…”)
}
response.json(users);
});
});

//API ENDPOINT(3) - POST /api/users/:_id/exercises. doublecheck it later
const apiUserExcercisePath = ‘/api/users/:id/exercises’;

app.post(apiUserExcercisePath, (request, response) => {
let userId = request.body.id,
description = request.body.description,
duration = request.body.duration,
date = request.body.date;

//Date format.
const options = { weekday: ‘short’, year: ‘numeric’, month: ‘short’, day: ‘numeric’ };

//date format condition.
if (date === “”) {
const currentDate = new Date();
date = currentDate.toLocaleDateString(undefined, options);
}else if (date.includes("-") || date.includes(" “) || date.includes(”/")) {
const currentDate = new Date(date);
date = currentDate.toLocaleDateString(undefined, options);
}

const newExcerciseRecord = new SessionLogs({
  "description": description,
  "duration": Number(duration),
  "date": date
});

UserRecords.findOneAndUpdate(
  {"_id": userId}, 
  {$push: {"log": newExcerciseRecord}}, 
  {new: true}, 
  (error, updatedRecord) => {
  if (error) {
  console.log(error);
  response.send("Something went Wrong... Check //API ENDPOINT(3)");//used to check which part of the code is having an error
  }

  let responseObject = {};
  responseObject['username'] = updatedRecord.username; //this is the problem during the testing via Freecodecamp Exercise Tracker. 
  responseObject['description'] = newExcerciseRecord.description;
  responseObject['duration'] = newExcerciseRecord.duration;
  responseObject['date'] = newExcerciseRecord.date;
  responseObject['_id'] = userId;
  
  response.json(responseObject);
  console.log(userId);
  console.log(updatedRecord);// the user's updated record is showing in the console and the required output is showing 
  console.log(updatedRecord.username)// user's username is being pulled out from mongo db in the console using console.log()
});
});

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

This is the link to the full project: https://replit.com/@Luderio/boilerplate-project-exercisetracker#.replit

Log your route inputs and the updatedRecord and you’ll see the problem:

app.post(apiUserExcercisePath, (request, response) => {
  console.log(`req.body: ${JSON.stringify(request.body)}`);
  console.log(`req.params: ${JSON.stringify(request.params)}`);
  console.log(`req.query: ${JSON.stringify(request.query)}`);

  let userId = request.body[':_id'],

logs

req.body: {"description":"test","duration":"60","date":"1990-01-01"}
req.params: {"_id":"61bfd87a37f438010b39fd87"}
req.query: {}

and updatedRecord is

null

Look closely at how you define userId and where the _id is set. The find() that sets updatedRecord does not have the correct input.

1 Like

Thank you so much for explaining this to me. It is now resolved. :smiley: