Exercise Tracker Failing Tests for GET api/users/:_id/logs – Back End Development and APIs Projects

I keep failing the GET /api/users/:_id/logs part of this project. It works for me when I test it myself (the logs show as they’re supposed to, including when using the from, to, and limit parameters). But when I submit my code, it fails. I’ve spent a lot of time trying my best to figure out what’s going wrong, but I’m completely stumped. Any guidance is appreciated.

require('dotenv').config();

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const uri = process.env.MONGODB_URI;
const app = express();
const port = process.env.PORT || 3000;

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

// Connect to database
mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true});

// Username schema and model
const userSchema = new mongoose.Schema({
  username: { type: String, required: true }
});

const User = mongoose.model('User', userSchema);

// Exercise schema and model
const exerciseSchema = new mongoose.Schema({
  username: { type: String, required: true },
  description: { type: String, required: true },
  duration: { type: Number, required: true },
  date: String,
  userId: String
});

const Exercise = mongoose.model("Exercise", exerciseSchema);


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

// New user
app.post("/api/users", (req, res) => {
  const username = req.body.username;
  
  createNewUser(username);

  async function createNewUser(username) {
    const newUser = new User({
      username: username
    });

    await newUser.save();

    // Return new user as json response
    User.findOne({ username: username }, function(err, doc) {
      if (err) {
        console.log("There was an error finding the new user in database.");
      } else {
        return res.json({
          username: doc["username"],
          _id: doc["_id"]
        });
      }
    })
  }
});

// Array of all users
app.get("/api/users", (req, res) => {
 
  User.find({}, function (err, docs) {
    if (err) {
      console.log("There was an error finding all users");
    } else {
      res.send(docs);
    }
  });  
});

// New exercise entry
app.post("/api/users/:id/exercises", (req, res) => {
 
  const userId = req.params.id;
  const description = req.body.description;
  const duration = Number(req.body.duration);
  const dateInput = req.body.date;

  let username = "";
  let date = "";

  User.findById(userId, function(err, doc) {
    if (err) {
      console.log("error finding user by userid");
    } else {
      username = doc.username;

      // Format the date as a string (use current date if input field is blank)
      if (dateInput.length != 0) {
        date = new Date(dateInput.replace(/-/g, '\/')).toDateString();
      }
      if (dateInput.length == 0) {
        date = new Date().toDateString();
      }

      const newExercise = new Exercise({ username: username, description: description, duration: duration, date: date, userId: userId });
      newExercise.save();

      res.json({ _id: userId, username: username, date: date, duration: duration, description: description });
    }
  });
});

app.get("/api/users/:id/logs", (req, res) => {

  const userId = req.params.id;
  const from = req.query.from;
  const to = req.query.to;
  const limit = req.query.limit;
 
  let exerciseLogs = [];
  let logCount = 0;
  let username = "";

  Exercise.find( {userId: userId}, function(err, exercises) {
    if (err) {
      console.log("error finding exercises by userid");
    } else {
      exercises.forEach((exercise) => {
        exerciseLogs.unshift({description: exercise.description, duration: exercise.duration, date: exercise.date});
      });
      
      if (from) {
        const dateFrom = new Date(from.replace(/-/g, '\/')); //replace - with / so date isn't one day off
        exerciseLogs = exerciseLogs.filter(log => new Date(log.date) >= dateFrom);
      }
      if (to) {
        const dateTo = new Date(to.replace(/-/g, '\/')); //replace - with / so date isn't one day off
        exerciseLogs = exerciseLogs.filter(log => new Date(log.date) <= dateTo);
      }
      if (limit) {
        exerciseLogs = exerciseLogs.slice(0, limit);
      }

      logCount = exerciseLogs.length;
    }

    User.findById(userId, function(err, doc) {
      if (err) {
        console.log("error finding username by userid");
      } else {
        username = doc.username;
        res.json({ _id: userId, username: username, count: logCount, log: exerciseLogs });
      }
    });
  });
});

const listener = app.listen(port, () => {
  console.log('Your app is listening on port ' + listener.address().port);
});

solution: https://exercise-tracker-dottibug.herokuapp.com

Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

Look at your browser console when submitting the url of your project. You are seeing those errors because you do not have CORS configured to allow any site to connect to your app.

Thanks! I did try to fix the issue using this article from FCC, but I still get the same errors in my browser console.

Checkout this documentation on the subject.

Thanks again! I did read that before posting and have it written that way in the original code I posted. I guess it’s still over my head or I’m missing some important detail, because it still doesn’t work when I submit the solution.