I finished the API Exercise Tracker challenge but wondering if there’s a more elegant way to write the code that filters for dates of the exercise…?
This is my Schema - exercises is in an Array
let profileSchema = new Schema({
username: { type: String, trim: true, default: "" },
exercises: [
{
description: { type: String, trim: true, default: "" },
duration: { type: Number, trim: true, default: "" },
date: { type: Date, trim: true, default: "" }
}
]
});
This is code works but not as elegant as it could be:
app.get("/api/exercise/log/:userId", async (req, res) => {
let id = req.params.userId,
fromDate = new Date(req.query.from),
toDate = new Date(req.query.to),
limit = req.query.limit;
try {
/*--- How to make this more elegant? ---*/
let profile = await Profile.findById(id);
profile.exercises = profile.exercises.filter(x => {
return (x.date>=fromDate && x.date<=toDate);
});
profile.exercises = profile.exercises.slice(0,limit);
/*--- How to make this more elegant? ---*/
res.json(profile);
} catch {
return new Error(`Error showing profile for id ${id}.`);
}
});
How can I write it more elegantly using Mongoose? Below is what I came up with but it doesn’t work.
let profile = await Profile.find({"_id": id}, {"exercises.date": {$gte: fromDate, $lte: toDate}}); // somehow also needs to select only 'limit' number of dates...