Not able to solve the last test case on Exercise tracker - Backend APIs and Microservices Certification

I am not able to pass the last test case on the above project , no matter how much I try!

When I try to execute it manually, it gets executed but the test is not passing! Worst part is I am not able to figure out also where is the error! Please help me! This is a cry for help. I am on the verge of giving up backend dev.

This is my code -

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

const mng = require('mongoose');
const bdp = require('body-parser');
const mmt = require('moment');

const { Schema } = require('mongoose');
/*-------------------------Mongoose Connection--------------------------------*/
mng.connect(process.env['Con_url'], { useNewUrlParser: true });
if (!!mng.connection.readyState === true) {
    console.log('connected!');
}
else {
    console.log('some errors!!!');
}
/*----------------------------------------------------------------------------*/

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





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

app.use(bdp.urlencoded({ extended: false })); // middleware for post requests.

const userSchema = new Schema({
    username: {
        type: String,
        requried: true
    },
    count: {
        type: Number,
        default: 0
    },
    log: [{
        date: String,
        duration: Number,
        description: String
    }]
})

const Users = mng.model('Users', userSchema);
//console.log(typeof(mmt('2022-05-14').format('ddd MMM DD YYYY')));


// Creating unique users based on name!

app.route('/api/users').post((req, res) => {
    //console.log('request body', req.body);

    let u_name = req.body.username;

    Users.find({ username: u_name }, (err, data) => {
        if (err) {
            res.send('Not able to find in DB!')
            return console.log(err);
        }
        else if (data.length == 0) {
            let users = new Users({
                username: u_name
            });
            users.save((err, user) => {
                if (err) {
                    res.send('error in saving user');
                    return consoe.log(err);
                }
                //console.log(user);
                res.json({
                    username: user.username,
                    _id: user._id
                });
            })
        }
        else {
            console.log('Already data is present -> ', data);
            res.send('User already exists!!');
        }
    })

}).get((req, res) => {
    Users.find({}, (err, users) => {
        if (err) {
            res.send('Error in finding users in DB!');
            return console.log(err);
        }
        res.send(users);
        //console.log(users);
    })
})

// Posting user exercises in database - 

app.post('/api/users/:_id/exercises', (req, res) => {
    //console.log(req.body);

    let u_id = req.params._id;

    let reqDate = req.body.date;
    if (reqDate === '') {
        reqDate = new Date().toISOString().substring(0, 10);
    }

    let u_logs = {
        date: mmt(reqDate).format('ddd MMM DD YYYY'),
        duration: parseInt(req.body.duration),
        description: req.body.description
    };

    Users.findByIdAndUpdate({ _id: u_id }, { $push: { log: u_logs }, $inc: { count: 1 } }, { new: true }, (err, data) => {
        if (err) {
            res.send('Error in updating records in DB!');
            return console.log(err);
        }
        //console.log(data);
        res.json({
            _id: data._id,
            username: data.username,
            ...u_logs
        });
    })

})

// Getting user exercises logs 

/*app.get('/api/users/:_id/logs', (req, res) => {

	let { from, to, limit } = req.query;

	if (from) {
		from = mmt(from).format('ddd MMM DD YYYY');
	}
	if (to) {
		to = mmt(to).format('ddd MMM DD YYYY');
	}
	if (limit) {
		limit = parseInt(limit);
	}

	Users.findById(req.params._id, (err, user) => {
		if (err) {
			res.send('Error in finding the user in DB');
		}

		console.log('user -> ', user);

		let logs = user.log;

		if (limit) {
			logs = logs.slice(0, limit);
		}

		if (from || to || limit) {
			console.log('responding for from-to-limit')
			res.json({
				_id: user._id,
				username: user.username,
				count: logs.length,
				log: logs
			})
		}
		else {
			console.log('responding for normal one')
			res.json({
				_id: user._id,
				username: user.username,
				count: logs.length,
				log: user.log
			})
		}
	})
})*/ // this is giving me tests timed_out.

app.get('/api/users/:_id/logs', (req, res) => {
    console.log(req.query);

    let { from, to, limit } = req.query;
    let u_id = req.params._id;
    if (from) {
        from = mmt(from).format('ddd MMM DD YYYY');
    }
    if (to) {
        to = mmt(to).format('ddd MMM DD YYYY');
    }
    if (limit) {
        limit = parseInt(limit);
    }

    if(from || to || limit) {

        console.log('Query block!!');
        if (limit) {
            console.log('With limit = ', limit);
            Users
                .findById(u_id)
                .limit(limit)
                .exec((err, user) => {
                    if (err) {
                        res.send('error in finding user');
                        return console.log(err);
                    }
                    console.log(user);
    
                    let u_logs = user.log;
                    if (from) {
                        u_logs = { ...u_logs, $gte: from };
                    }
                    if (to) {
                        u_logs = { ...u_logs, $lte: to };
                    }
    
                    res.json({
                        _id: user._id,
                        username: user.username,
                        count: parseInt(u_logs.count),
                        log: u_logs
                    });
                })
        }
        else {
            console.log('without limit');
            Users.findById(u_id, (err, user) => {
                if (err) {
                    res.send('error in finding user');
                    return console.log(err);
                }
                console.log(user);
    
                let u_logs = user.log;
                if (from) {
                    u_logs = { ...u_logs, $gte: from };
                }
                if (to) {
                    u_logs = { ...u_logs, $lte: to };
                }
    
                res.json({
                    _id: user._id,
                    username: user.username,
                    count: parseInt(u_logs.count),
                    log: u_logs
                });
            })
        }
    }
    else {
        console.log('No query block!!');
        Users.findById(u_id, (err, user) => {
            if(err) {
                res.send('error in finding user in DB!');
                return console.log(err);
            }
            //console.log(user);
            res.send(user);
        })
    }
})




// Deleting all users at once - 

app.get('/api/delete-all', (req, res) => {
    Users.deleteMany({}, (err, user) => {
        if (err) {
            res.send('Error in deleting')
            return console.log(err);
        }
        //console.log(user);
        res.send(user);
    })
})

This is the error I am getting when trying to pass the test cases -

You can add from, to and limit parameters to a GET /api/users/:_id/logs request to retrieve part of the log of any user. from and to are dates in yyyy-mm-dd format. limit is an integer of how many logs to send back.

Any sort of help will be appreciated . Please someone reach out to me. Many thanks!

Someone, anyone , please help me to understand and resolve this issue as soon as possible !

Thank you.

Please post a link to your Replit.

Hi @lasjorg . Thank you very much for the response. Here is the Replit link -

Replit Link

Please note that, now when I try to execute the code again, it is giving me the date error to which previously it was not there.

Below is the date error -

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.

Please help me to understand what mistake am I doing here and how do I correct it.

Thank you.

I can’t really look at the code now but I would suggest you try it without Moment.js or at least make sure what it is giving you is the same as what the requirement wants.

@lasjorg ,

The requirement states the dates to be in string format and I have done exactly that. I have used Moment.js to just format it in the asked format. With the Date object, it seems to be difficult and the test case was failing repeatedly. With Moment.js, it actually worked. But all of a sudden, I am getting the error again.

Besides, when I try to execute similar requests manually, I get the result exactly like it is shown in the example solution link that is provided in the project.

If you can please have a look at the code, that would be really helpful because I am not able to understand where exactly the mistake is.

The last date test is passing for me. I think you have to not test that near midnight as there might be some daylight-saving issues with that test.

The filter test (to/from/limit) is however not returning the correct response (look at properties for the dates). Looks like the comparison query operators are getting used as properties.

{"_id":"62c314fb825c898610023b90","username":"fcc_test_16569520602","count":null,"log":{"0":{"date":"Mon Jan 01 1990","duration":60,"description":"test","_id":"62c314fb825c898610023b92"},"1":{"date":"Wed Jan 03 1990","duration":60,"description":"test","_id":"62c314fc825c898610023b94"},"$gte":"Sun Dec 31 1989","$lte":"Thu Jan 04 1990"}}

@lasjorg , thank you very much for identifying the mistake. Could you possibly suggest any correction here please? That would actually help me to understand what mistake am I making. Is it the syntax or the logic of the comparison.

Thanks again.

The log property is supposed to be an array of objects filtered by date (to/from). Personally, I think it is easier to just use JS and filter the log array by date.

1 Like

@lasjorg , Thank you very much for your suggestion. But, I am going to have to trouble you a little more. :sweat_smile:

I have corrected the log property as you asked, and now when I am manually executing it, I can see the same results as in template site. But the test is still failing. Now it gives the time-out error.

You can add from, to and limit parameters to a GET /api/users/:_id/logs request to retrieve part of the log of any user. from and to are dates in yyyy-mm-dd format. limit is an integer of how many logs to send back. (Test timed out)

I have also attached screenshot of the manual execution with the query parameters, if that helps in anyways -

Please help me to fix this and also if you could possibly tell me why is this error occurring, that would very helpful.

Thank you.

You seem to have fixed it, at least your code is passing for me.

@lasjorg ,

Still got the same error :sob:. I tried to execute this in private window as well. I was using Mozilla and then I used Brave browser. But, no change. Would you suggest to use Chrome to mitigate this ? At least I am relieved that there is nothing wrong with the code, right ?

Also, a favor If I could ask, could you give any sorts of suggestions or opinions on my code, if there is any, that would be very helpful :sweat_smile::grin:.

thanks again.

Well, your code is definitely passing for me. The browser really shouldn’t matter here.

I know some people have success with using VPNs for whatever reason. It can also be worth doing a fork of your project with the VPN active as it can put the code on a different server.

I can’t say much about the code and all that really matters at this point is that the code works. I will say I’m not personally a fan of short variables unless they are super obvious. Sure u_id is likely the user id in this context but it might be a unique id or something else starting with u. I’d just use userId, or user_id it’s more clear to anyone else reading the code. Better to have a long descriptive variable name than something that might be ambiguous.

You might also use the actual property name with destructuring:

let u_name = req.body.username;
Users.find({ username: u_name } ...code)

VS

const { username } = req.body;
Users.find({ username } ...code)

The fewer variable names you have to keep track of in your head, and the clearer the names, the better.

1 Like

@lasjorg,

Well, finally the code worked! I couldn’t thank you enough for all of your suggestions. I will make sure to use fewer variables and clearer names in the future.

This is the very first course I did on back-end dev. I would very much appreciate it if you have any sorts of suggestions or advice as to what should be the next step towards building a career in it.

And again, thank you very much for all your help and suggestions.