Exercise Tracker not passing tests when I think it should

Hello. I am having trouble submitting the exercise tracker project for the backend APIs certificate.

I have two tests that are failing and I am unsure why. These are the tests:

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

The date property of any object in the log array that is returned from GET /api/users/:_id/logs should be a string. Use the dateString format of the Date API.

Provided below is the code I am trying to submit:

const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
const mongoose = require('mongoose');
const { Schema } = mongoose;

mongoose.connect(process.env.DB_URL);

const UserSchema = new Schema({
  username: String,
});
const User = mongoose.model("User", UserSchema);

const ExerciseSchema = new Schema({
  user_id: { type: String, required: true },
  description: String,
  duration: Number,
  date: Date,
});

const Exercise = mongoose.model("Exercise", ExerciseSchema)

app.use(cors())
app.use(express.static('public'))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

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

app.post('/api/users/', async (req, res) => {
  const userObj = new User({
    username: req.body.username
  })

  try {
    const user = await userObj.save();
    res.json(user);
  }
  catch (err) {
    console.log(err);
  }
});

app.post('/api/users/:_id/exercises', async (req, res) => {

  const id = req.params._id;
  const { description, duration, date } = req.body;

  const user = await User.findById(id);

  const exerciseObj = new Exercise({
    user_id: user._id,
    description,
    duration,
    date: date ? new Date(date).toDateString() : new Date().toDateString()
  });

  const exercise = await exerciseObj.save();

  res.json({
    _id: user._id,
    username: user.username,
    description: exercise.description,
    duration: exercise.duration,
    date: new Date(exercise.date).toDateString()
  });
}

);

app.get('/api/users', async (req, res) => {
  const users = await User.find({}, '_id username');
  if (!users) {
    res.send("No users");
  }
  res.json(users);
});

app.get("/api/users/:_id/logs", async (req, res) => {
  const { from, to, limit } = req.query;
  const id = req.params._id;
  const user = await User.findById(id);

  let dateObj = {}

  if (from) {
    dateObj['$gte'] = new Date(from);
  }

  if (to) {
    dateObj['$lte'] = new Date(to);
  }
  let filter = {
    user_id: id,
  }

  if (from || to) {
    filter.date = dateObj;
  }

  const exercises = await Exercise.find(filter).limit(+limit ?? 500);

  const result = exercises.map(e => ({
    description: e.description,
    duration: e.duration,
    date: e.date.toDateString()
  }))

  res.json({
    username: user.username,
    count: exercises.length,
    _id: user._id,
    log: result
  })

})

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

Given this, I am unsure as to why these tests are failing. I’ve checked the network logs from my browser and all of the responses appear correct. I’ve browsed these forums/Youtube looking for solutions but I cannot find anything unfortunately. I feel like these tests should be passing but I can’t figure out what’s wrong. If I can provide anything else that will provide more clarity to the issue I am facing, I am more than willing to send it over.

Also, I cannot use repl.it for this project. I get errors if I try to import the boilerplate code to repl.it Or, if I try to copy my code to repl.it, any function that uses async/await will time out and will subsequently not run (only when testing through FCC is when it times out). I am at a loss for what to do and will greatly appreciate any help.

Sidenote: The second test regarding the datestring will pass randomly and fail other times even if I made no changes. Not sure what’s happening there.

Hey @irvinb35,

I had a hard time to pass all tests too. I tried again today and all tests passed, it look like the platform is working fine. If you want to look here is my project:

boilerplate-project-exercisetracker - Replit

Try to use Replit, what error did you get when you try to import the boilerplate?

I dont know if it is the problem, but I changed the order of the properties in res.json inside app.post(‘/api/users/:_id/exercises’) to be the same as the example.

    res.json({
      _id: user._id,
      username: user.username,
      date: new Date(result.date).toDateString(),
      duration: result.duration,
      description: result.description,
    });

Another thing in your code I think can improve is to make the values of duration property of result to a number inside app.get(“/api/users/:_id/logs”) route.

  const result = exercises.map(e => ({
    description: e.description,
    duration: parseInt(e.duration),
    date: e.date.toDateString()
  }))

Hope you get the solution soon!

Hi! Thanks for responding.

I would love to use repl.it because it appears it fixes some of the issues for others, but I cannot get it to work. When I try to import from github, I get an error saying “This repository could not be accessed, try again later”. But like I said, even if I try to copy/paste my code from local to repl.it, any async/await functions that get called will time out the server no matter what. I’m not sure how to get around that.

Beyond that, I tried changing the order and using parseInt() like you said and it still gives me the same errors. Also, the second test is passing again (before I made any adjustments), but I’m unsure as to why. First test still fails as usual.

If there is anything else I could do please let me know! Thanks for your help.

Not sure if anyone else will stop here, but I did find something interesting. While checking the network logs, I notice some of the “exercises” and “logs” responses contain empty responses. I check the timing and I see this:
image

I am unsure of what to do with it. I tried to force a timeout before my res.json() but it doesn’t seem to work. I tested this in Microsoft Edge as well and got the same result. If anyone has any ideas on how to get around this I’d appreciate it.

The code you posted is passing for me both locally and on Replit. So I’m pretty sure it is something on your end.

If it isn’t the browser maybe it is your network/connection.

You can try creating a new collection to make sure there isn’t an issue on the DB side of things.

You can try using Glitch instead of Replit. Remember it has to be online so you can’t pass this using localhost anyway.

Hey! Yeah, it has to be some sort of connection issue. I’ve disabled windows firewall, I deleted and recreated my cluster on mongo as you suggested, and in my previous post I mentioned I already used glitch. Same problem as replit. Any time an await function is called the program stalls and the tests timeout =/

Any other ideas?

Not sure, but if it fails both locally, on Replit and Glitch, it must be something local to your system. Maybe you can try submitting from a different system? Create a Replit and submit it from your phone maybe? You can also try using a VPN to see if that changes anything.


Considering you are using async/await in the other route handlers and they are not failing the tests I don’t see this being the issue.

Yeah, I’m assuming it’s something locally wrong as well. Just can’t figure it out. Tried submitting my phone. Same problem. Tried using a VPN, doesn’t work.

The reason I say async/await does not work is because if I try putting console.log()'s around it, I can see the program stalling on that await function call. Again, it only stalls if trying to test via repl.it/glitch. Here is the error:
image

One of the functions is timing out. I’m not sure why it runs fine on my machine but it times out on repl.it. Is there a workaround for this function/issue?

Thank you for trying to help btw! I really appreciate the input even if this is feels impossible to get around.

I’m wondering if I can complete this locally without mongoose. I did that for the URL shortener. Instead of using MongoDB for the URLs, I just used a basic list to store everything locally on my machine.

Looks to be the DB. Did you whitelist all IPs 0.0.0.0/0 in the settings?

Thank you so much! That solved it. Now I’ll remember to check that in the future. You’ve been a huge help.

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