我已经尝试了所有的解决方案,我可以在这里找到,但我仍然想出0记录,但不知道为什么!
设想情况:
每天都有通话记录。每天的总呼吁
守则:
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');
}
mongodb中调用记录的示例
结果:
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)
发布于 2022-09-29 04:44:17
当add
ing时,Momentjs会变异原始对象,而不会创建新对象。
因此,您需要克隆对象;否则,您将向MongoDB发送一个命令:“给我在明天和明天(同一日期)之间创建的文档”,这显然不是您想要的。
const cdrIns = await CDRIn.find({
createdAt: {
$gte: today.clone(),
// without cloning, .add(...) changes the object above as well
$lt: today.clone().add(1, 'day').toDate()
},
});
发布于 2022-09-29 04:37:29
尝试使用toISOString()
格式化日期
const cdrIns = await CDRIn.find({
createdAt: {
$gte: today.toISOString(),
$lt: today.add(1, 'day').toISOString(),
},
});
https://stackoverflow.com/questions/73895560
复制