Exercise Tracker Project Test Fails

Even though I get the same result as freecodecamp’s example, tests fails. I really don’t know why that happens.

My Code:

const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require("mongoose")
const bodyParser = require('body-parser')
require('dotenv').config()

//Connect to MongoDB Atlas and create schemas
mongoose.connect(process.env.MONGO_URI, {
    useUnifiedTopology: true,
    useNewUrlParser: true
});

const { Schema } = mongoose;

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

const UserSchema = new Schema({
    username: String,
})

const user = mongoose.model("User", UserSchema)
const exercise = mongoose.model("Exercise", ExerciseSchema)



app.use(bodyParser.urlencoded({ extended: false })); //
app.use(bodyParser.json());
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/views/index.html')
});

//1. You can POST to /api/users with form data username to create a new user.
app.post("/api/users", (req, res) => {
    console.log('req.body', req.body);
    const newUser = new user({
        username: req.body.username
    })
    newUser.save((err, data) => {
        if (!data || err) {
            res.send("There was an error saving the user")
        } else {
            res.json(data)
        }
    })
})

app.post("/api/users/:id/exercises", (req, res) => {
    const id = req.params.id
    const { description, duration, date } = req.body
    user.findById(id, (err, userData) => {
        if (err || !userData) {
            res.send("Couldn't find the user")
        } else {
            const newExercise = new exercise({
                userId: id,
                description,
                duration,
                date: new Date(date),
            })
            newExercise.save((err, data) => {
                if (err || !data) {
                    res.send("There was an error saving this exercise")
                } else {
                    const { description, duration, date, _id } = data;
                    res.json({
                        _id: userData.id,
                        username: userData.username,
                        date: date.toDateString(),
                        duration: Number(duration),
                        description
                    })
                }
            })
        }
    })

})

app.get("/api/users/:id/logs", (req, res) => {
    const { from, to, limit } = req.query;
    const { id } = req.params;
    user.findById(id, (err, userData) => {
        if (err || !userData) {
            res.send("Could not find the user.")
        } else {
            let dateObj = {}
            if (from) {
                dateObj["$gte"] = new Date(from)
            }
            if (to) {
                dateObj["$lte"] = new Date(to)
            }
            let filter = {
                userId: id
            }
            if (from || to) {
                filter.date = dateObj
            }
            let nonNullLimit;
            if (limit === "null") {
                nonNullLimit = 500
            }
            exercise.find(filter).limit(+nonNullLimit).exec((err, data) => {
                if (err || !data) {
                    res.json([])
                } else {
                    const count = data.length
                    const rawLog = data
                    const { username, _id } = userData;
                    const log = rawLog.map((l) => ({
                        description: l.description,
                        duration: l.duration,
                        date: l.date.toDateString()
                    }))
                    res.json({ _id, username, count, log })
                }
            })
        }
    })
});

//The GET request to /api/users returns an array.
app.get("/api/users", (req, res) => {
    user.find({}, (err, data) => {
        if (!data) {
            res.send("No users")
        } else {
            res.json(data)
        }
    })
})

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

These are the fail tests:

Live replit version: https://Exercise-Tracker.bbsemih.repl.co

Could you help me ASAP ?

One of the user stories is:

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.

Try submitting an exercise without a date and see what your app does.

It returns the error I’ve written right there :

newExercise.save((err, data) => {
                if (err || !data) {
                    res.send("There was an error saving this exercise")
                }

It is the screenshot :
Ekran Resmi 2022-08-12 20.51.16

Btw as you can see from the tests, I guess it is all about logs. But the format is exactly the same as freecodecamp’s example. You can see my version on replit.

The point is it should not error out if the user does not supply a date for the exercise. If you console.log(err) you will see what the actual issue is.

Oh I see. I’m sorry.

{"errors":{"date":{"stringValue":"\"Invalid Date\"","valueType":"Date","kind":"date","value":null,"path":"date","reason":{"generatedMessage":true,"code":"ERR_ASSERTION","actual":false,"expected":true,"operator":"=="},"name":"CastError","message":"Cast to date failed for value \"Invalid Date\" (type Date) at path \"date\""}},"_message":"Exercise validation failed","name":"ValidationError","message":"Exercise validation failed: date: Cast to date failed for value \"Invalid Date\" (type Date) at path \"date\""}

That’s the error I get.

Narrow it done a bit:

console.log(err.message)

Now do you understand why you are getting the error message?

1 Like

Yes I understood and managed to fix the majority of tests but I didn’t understand those 2 tests.

It looks completely same with fcc’s version.

You keep saying that. However, if you do not pass a date to fcc’s version, you still get a JSON reponse (not an error like yours).

I don’t get error anymore when I don’t pass a date, I fixed that. That’s why I said it looks completely same with fcc’s version.

Unless you are testing out a different project than you posted above, I see:

exer

I didn’t make any changes in replit. I did on my local machine. Wait a second. Sorry.

Can you check now ? Now, when you don’t pass a date, it automatically returns the current date.

Your issue is related to the timezone difference between the timezone of the server and your local timezone.

You can checkout these topics to see the issue.

There is a way to deal with your timezone issue if you make use of Date.prototype.getTimezoneOffset

Another option is to look at the difference between the HTTP response header time to the servers to figure out how much to offset.

1 Like