Hi, FCC folks. I just finished the exercise tracker project for the APIs and Microservices certification, and while my code passes all the tests, the way I went about implementing the last requirement, (“I can retrieve part of the log of any user by also passing along optional parameters of from & to or limit. (Date format yyyy-mm-dd, limit = int),”) is pretty ugly, and I know there must be a better way to go about this using Mongoose queries. My model for each user is as follows:
let exerciseSchema = new mongoose.Schema({
description: { type: String, required: true },
duration: { type: Number, required: true },
date: { type: Date, default: Date.now()}
});
let userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
_id: { type: String, default: shortid.generate },
exercises: [exerciseSchema]
});
let User = mongoose.model("User", userSchema);
My “/api/exercise/log” code looks like this:
app.get('/api/exercise/log', (req, res) => {
let log = [];
let qLimit = req.query.limit;
let qFrom = req.query.from;
let qTo = req.query.to;
User.findOne({_id: req.query.userId}, (err, data) => {
if (err) {
res.send(err);
}
log = data.exercises.slice();
if (qFrom && !qTo) {
log = log.filter(item => new Date(item.date).getTime() > new Date(qFrom).getTime());
} else if (!qFrom && qTo) {
log = log.filter(item => new Date(item.date).getTime() < new Date(qTo).getTime());
} else if (qFrom && qTo) {
log = log.filter(item => new Date(item.date).getTime() > new Date(qFrom).getTime()
&& new Date(item.date).getTime() < new Date(qTo).getTime());
}
if (qLimit) {
log = log.slice(0, qLimit);
}
res.send({
username: data.username,
_id: data._id,
count: data.exercises.length,
log: log
});
})
})
This doesn’t strike me as the “right” way to do this, but I’m a little lost on how I could have used the built-in Mongoose query stuff on a sub-schema like I have here.
The challenge: https://www.freecodecamp.org/learn/apis-and-microservices/apis-and-microservices-projects/exercise-tracker
My full project: https://glitch.com/edit/#!/luos-fcc-exercise-tracker?path=server.js:138:0
Thanks for your time!