I’ve tried all solutions I could find on here, but I am still coming up with 0 records and not sure why!
Scenario:
Get call records for each day. Output total calls for each day
The code:
const startOfMonth = new moment().startOf('month');
const yesterday = new moment().subtract(1, 'day');
const now = startOfMonth.clone();
while (now.isSameOrBefore(yesterday)) {
const today = now.clone();
const cdrIns = await CDRIn.find({
createdAt: {
$gte: today,
$lt: today.add(1, 'day')
},
});
console.log(`There were ${cdrIns.length} calls on ${today.toDate()}`)
now.add('1', 'day');
}
Sample of a call record in mongodb
Results:
There were 0 calls on Thu Sep 22 2022 00:00:00 GMT-0500 (Central Daylight Time)
There were 0 calls on Fri Sep 23 2022 00:00:00 GMT-0500 (Central Daylight Time)
There were 0 calls on Sat Sep 24 2022 00:00:00 GMT-0500 (Central Daylight Time)
There were 0 calls on Sun Sep 25 2022 00:00:00 GMT-0500 (Central Daylight Time)
There were 0 calls on Mon Sep 26 2022 00:00:00 GMT-0500 (Central Daylight Time)
There were 0 calls on Tue Sep 27 2022 00:00:00 GMT-0500 (Central Daylight Time)
There were 0 calls on Wed Sep 28 2022 00:00:00 GMT-0500 (Central Daylight Time)
There were 0 calls on Thu Sep 29 2022 00:00:00 GMT-0500 (Central Daylight Time)
2
Answers
Try to format the dates using
toISOString()
:Momentjs mutates original objects when
add
ing, it does not create a new one.So you need to clone the object; otherwise, you’re sending a command to MongoDB saying, "get me the documents that are created between tomorrow and tomorrow (same date)", which is clearly not what you want.