Alright, here’s the breakdown and walkthrough of my code:
First I’m checking if there’s a from and to date range, then if there is, checking to see if there’s a limit
if (fromDate && toDate) {
fromDate = new Date(fromDate);
toDate = new Date(toDate);
if (fromDate == ‘Invalid Date’ || toDate == ‘Invalid Date’) {
return res.json(‘Invalid parameters’);
}
if (limit) {
if (limit <= 0) {
return res.json(‘Invalid number’);
} else {
user.findById({_id: id, date: {$gte: fromDate, $lte: toDate}})
.limit(limit)
.then(function(logs, err){
if(err) console.error(err);
let log = logs.log;
let count = limit;
console.log({username: logs.username, _id: id, limit: limit, count: limit, log: log});
res.json({username: logs.username, _id: id, count: limit, log: log});
})
}
user.findById({_id: id, date: {$gte: fromDate, $lte: toDate}})
.then(function(logs, err){
if(err) console.error(err);
let log = logs.log;
let count = log.length;
console.log({username: logs.username, _id: id, count: count, log: log});
res.json({username: logs.username, _id: id, count: count, log: log});
})
}
}
If there is no date, we then look for just a limit. This seems like where it’s going wrong, as when I try to return a limited number of results, the program doesn’t limit the results, even when using ‘.limit’ in the ‘findById’ function
else {
if (limit) {
if (limit <= 0) {
return res.json(‘Invalid number’);
} else {
user.findById({_id: req.params._id})
.limit(limit)
.then(function(logs, err) {
if(err) console.error(err);
let log = logs.log;
let count = limit;
// console.log({username: logs.username, _id: id, limit: limit, count: limit, log: log});
res.json({username: logs.username, _id: id, count: limit, log: log});
})
}
}
user.findById({_id: req.params._id})
.then(function(logs, err){
if(err) console.error(err);
let log = logs.log;
let count = log.length;
// console.log({username: logs.username, _id: id, count: count, log: log});
res.json({username: logs.username, _id: id, count: count, log: log});
})
}