Hello.
I am trying to list results between dates. https://learn.freecodecamp.org/apis-and-microservices/apis-and-microservices-projects/exercise-tracker
And here is my code:
// show exercises of user
router.get('/api/exercise/log', function(req, res, next) {
let userId = req.query.userId;
let from = new Date(req.query.from);
let to = new Date(req.query.to);
let limit = req.query.limit
User.findOne({ userId: userId}, function(err, user) {
if (err) {
next(err);
return;
} if (!user) {
res.json({ error: 'user not found!'});
} else {
let results = user.exercises
res.json({
exercises: results
});
}
})
});
GET users’s exercise log: GET /api/exercise/log?userId=userid&from=fromdate&to=todate&limit=howmanyitem
I spent 2 days for that. But I could not figure out any way.
Because of that I did not use the parameters. I dont know what to do.
I solved the problem. Thank you.
// show exercises of user
router.get('/api/exercise/log', function(req, res, next) {
let userId = req.query.userId;
let from = new Date(req.query.from);
let to = new Date(req.query.to);
let limit = req.query.limit;
User.findOne({ userId: userId}, function(err, user) {
if (err) {
next(err);
return;
} if (!user) {
res.json({ error: 'user not found!'});
} else {
let results = user.exercises
if(to && from) {
results = results.filter(function(item) {
return item.date >= from && item.date <= to
});
}
if(!isNaN(limit)) {
results = results.slice(0, limit);
}
res.json({
exercises: results
});
}
})
});
I have not yet completed the project, but in the local dev env, you can use
ExerciseLog.findById({ _id: req.query.userId },
{ "log":{ "$elemMatch" : { "date" : new Date(req.query.from).toISOString()}}}).exec( (err, data) => {
err?err: res.send("query data" + "<br />"+ data);
}) }
However, this code does not seems to work on https://glitch.com. I am not sure why.
The limit parameter can trick students because the coding challenges use the limit function. I was spending hours after hours before I finally realized that limit() or $limit applies only for rows(documents in MongoDB)
If you use $match and then $filter, you may not use $limit or limit() as you work with one row(document). you need to use Array.slice(0, limit) inside the callback function. But if you use $match and $unwind(to break one array into many), you may use limit() or $limit.
But, does this logic handles all permutations of from, to and limit parameters ?.