I have been looking around for some clues but I can’t seem to figure out how to retrieve a part of the log. Any help is greatly appreciated. Here is my code:
// 4. I can retrieve a full exercise log of any user by getting /api/exercise/log with a parameter of userId(_id).
// Return will be the user object with added array log and count (total exercise count).
// 5. 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)
app.get('/api/exercise/log', (req, res) => {
const {userId, from, to, limit} = req.query;
const log = getExercisesFromUserWithId(userId);
if(from){
const fromDate = new Date(from);
log = log.filter(exe => new Date(exe.date) > fromDate);
}
if(to){
const toDate = new Date(to);
log = log.filter(exe => new Date(exe.date) < toDate);
}
if(limit){
log = log.slice(0, limit);
}
res.json({
_id: userId,
username: getUsernameById(userId),
count: log.length,
log
});
});
hey there !
i’m on the same project right now !
i succeeded to pass the part of ‘retrieving the log’, & here is how i did that:
app.get('/api/exercise/log', function(req, res, next){
//get user id
let id = req.query.userId;
//check if id is not null
if(id){
userModel.findById(id, function(err, doc){
if(err) {return next(err);}
else{
//find all exercises which have the same userName
exerciseModel.find({'userName': doc.userName}, function(error, data){
//data retrieves array of logs
if(error){ return next(error); }
//we need to have both FROM and TO
if((req.query.from) && (req.query.to)){
data = data.filter((d)=> (Date.parse(d.date) >= Date.parse(req.query.from)) && (Date.parse(d.date) <= Date.parse(req.query.to)));
}
//check if index is smaller then LIMIT
if(req.query.limit){
data = data.filter((d,i)=> i < req.query.limit);
}
res.json({'_id': doc._id, 'userName': doc.userName, 'conunt': data.length, 'log':data});
})
}
})
}
})
so i think u have 2 problems.
1.u need to have in the IF condition both FROM & TO,
2.u can’t compare the Date object itself, so i parsed it to UNIX time (time in seconds), and then i compare it.
hope i helped
/ 5. 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)
app.get('/api/exercise/log', (req, res) => {
const {userId, from, to, limit} = req.query;
let temp=getExercisesFromUserWithId(userId);
if(from){
const fromDate= new Date(from)
temp = temp.filter(exe => new Date(exe.date) > fromDate);
}
if(to){
const toDate = new Date(to)
temp = temp.filter(exe => new Date(exe.date) < toDate);
}
if(limit){
temp = temp.slice(0,limit);
}
const log = {
_id:userId,
username:getUsernameById(userId),
count:parseFloat(temp.length),
log:temp
}
res.json(log)
});