I am struggling to pass this test on a freeCodeCamp project: "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. "
Here is the an example of the expected response:
{
username: "fcc_test",
count: 1,
_id: "5fb5853f734231456ccb3b05",
log: [{
description: "test",
duration: 60,
date: "Mon Jan 01 1990",
}]
}
I am returning the same as the example response
Here is my database query function:
export const fetchExerciseLogs = async (
userId: string,
from?: string,
to?: string,
limit?: string
): Promise<FetchExerciseLogsResult | undefined> => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const foundId: User | null = await UserModel.findById(userId)
// using username to find exercises associated with it
const exerciseQuery: exerciseQuery = {}
if (foundId) {
exerciseQuery.username = foundId.username;
}
// if there are request queries for date, add those to the query object
if (from && to) {
const fromDate = new Date(from);
const toDate = new Date(to);
exerciseQuery.date = { $gte: fromDate, $lte: toDate };
}
// if there is a limit query, change it to a number
let limitNumber: number = 9999
if (limit) {
limitNumber = parseFloat(limit);
}
// find all exercises in the db that match the username and any date and/or limit queries
const foundExercises = await ExerciseModel.find(exerciseQuery).limit(limitNumber).exec()
let logArray: ExerciseDetails[] | undefined = foundExercises.map((exercise) => {
return {
description: exercise.description,
duration: exercise.duration,
date: exercise.date,
};
})
// if there's a limit query - return log array no longer than the limit
if (limitNumber) {
logArray = logArray.slice(0, limitNumber + 1)
}
const numOfExercises: number = logArray.length;
const exerciseLog: FetchExerciseLogsResult = {
username: foundExercises[0]?.username || "no username found",
count: numOfExercises,
_id: userId,
log: logArray.length > 0 ? logArray : "no logs found"
}
return exerciseLog
};
Or alternatively, you can find the replit full code here: https://replit.com/@nicole-lancaste/boilerplate-project-exercisetracker
I have tried returning an empty array instead of the "no logs found" however this did not pass the test either. Thanks
Link to project requirements and user stories --> https://www.freecodecamp.org/learn/back-end-development-and-apis/back-end-development-and-apis-projects/exercise-tracker
Finally managed to sort the issues and got all tests passing.
Initially I changed the date format from toDateString()
to toUTCString()
however it appears Mongoose doesn't compare dates correctly in this format.
Last test passed with ensuring dates were stored in database using toISOString()
and only using the toDateString()
format when sending the response back to the user in the exercise/logs objects.