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 ?

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.

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.

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.

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.

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.

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