Exercise Tracker 8 & 15 API: POST: user object with the exercise fields added. GET: dateString format of the Date API

Hope can be good and kind of you if taking the time to read me post and try to help fix this. It has been 4 days and am unable to fix this maybe someone has had the same problem or something can be wrong with the testing. Did not want to ask and tried for several days have learned a lot while trying to fix this many times about format of api routes and structure of Express and Node that can be very good. I have rewrote code many times, have checked all websites even when it is the same problem does not work in me code, have checked the videos for this and tried those routes but did not work, and also AI is unable to fix it. Thank you take care gn gm frens.

// // running 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.

// // tests completed

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

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

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

const uri = process.env.MONGO_URI;
mongoose
  .connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Connected to MongoDB database'))
  .catch((error) => console.error('Failed to connect to database:', error));

const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: 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.now }
});

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

app.post('/api/users', async (req, res) => {
  const username = req.body.username;
  try {
    const user = new User({ username });
    await user.save();
    res.json({ username: user.username, _id: user._id });
  } catch (err) {
    console.error('Error creating user:', err);
    res.status(400).json({ error: err.message });
  }
});

app.get('/api/users', async (req, res) => {
  try {
    const users = await User.find({}, 'username _id');
    res.json(users);
  } catch (err) {
    console.error('Error fetching users:', err);
    res.status(400).json({ error: err.message });
  }
});

app.post('/api/users/:_id/exercises', async (req, res) => {
  const userId = req.params._id;
  let { description, duration, date } = req.body;

  try {
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    duration = Number(duration);
    if (isNaN(duration)) {
      return res.status(400).json({ error: 'Duration must be a number' });
    }

    date = date ? new Date(date) : new Date();
    if (date.toString() === 'Invalid Date') {
      date = new Date();
    }

    const exercise = new Exercise({
      userId: user._id,
      username: user.username,
      description,
      duration,
      date
    });

    await exercise.save();

    res.json({
      _id: user._id,
      username: user.username,
      date: date.toDateString(),
      duration: duration,
      description: description
    });
  } catch (error) {
    console.error('Error adding exercise:', error);
    res.status(500).json({ error: 'Server error' });
  }
});

app.get('/api/users/:_id/logs', async (req, res) => {
  const { from, to, limit } = req.query;
  const userId = req.params._id;

  try {
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    let dateObj = {};
    if (from) dateObj['$gte'] = new Date(from);
    if (to) dateObj['$lte'] = new Date(to);
    
    let filter = { userId: user._id };
    if (from || to) filter.date = dateObj;

    let exercises = await Exercise.find(filter).limit(Number(limit) || 0);

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

    res.json({
      _id: user._id,
      username: user.username,
      count: exercises.length,
      log: log
    });
  } catch (error) {
    console.error('Error fetching logs:', error);
    res.status(500).json({ error: 'Server error' });
  }
});

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

// // running 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.
// // tests completed

response with date can be string?
Screen Shot 2024-08-24 at 9.35.15 PM

Kind of you to take the time and check me vscode only looking for some positive helpful feedback nothing else have finished all the other fun exercises for the paper certification but this is not working with the user object response and also date toDateString() thank you take care gn gm frens.

Repositry webpage on Github

Hope can be doing good fixed 8 and 15 with extra changes and reading on the forum also here is link to other good information and where I found the start for the fixes:
https://forum.freecodecamp.org/t/back-end-development-and-apis-projects-exercise-tracker/674927

Just wanted to add some information also if someone else can have a problem with this, me have tried for 4 days with (8 & 15) now and am finally close to finishing it because of the error.

Used the checkDate function made but it did not work for me unless removing the arrow function, using just the if else statement, and changing the “return” to assigning it to a “date” variable but this made it work for #8.

app.post('/api/users/:_id/exercises', async (req, res) => {
  console.log('post exercises can be working')
  const userId = req.params._id; 
  console.log('userparam id working')

  let { description, duration, date } = req.body; 

  // if(!date){
  //   date = new Date()
  // } else {
  //   date = new Date(date)
  // }

  //changing returns to date =  and removing const dateChecker fixed: 
  // The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.
    if (!date) {
        date = (new Date(Date.now())).toDateString();
    } else {
        const parts = date.split('-');
        const year = parseInt(parts[0]);
        const month = parseInt(parts[1]) - 1;
        const day = parseInt(parts[2]);

        const utcDate = new Date(Date.UTC(year, month, day));
        date =  new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000).toDateString();
    }

  let foundUser = await User.findById(userId); 
 
  const newExercise = new Exercise({
    username: foundUser.username, 
    description, 
    duration: Number(duration),
    date,
    userId: userId, 
  })

  await newExercise.save()

  res.json({
    _id: foundUser._id,
    username: foundUser.username,
    description: newExercise.description,
    duration: newExercise.duration,
    date: newExercise.date.toDateString(),
  })
})

Now need to fix #15:
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.

Also me fixed 15 after a few posts about changing time settings and checking your chrome inspector/network/logs/headers to find the date being used by freeCodeCamp to run test probably was a day ahead and then changed computer date and time to be close to it and it fixed problem, took 4 days to find this and learned many good things for Express, routes and coding while doing this, kind of freecodecamp to offer this paper certificate.

Hopefully this can help someone else also.

Thank you take care