Mongoose / Mongoose 数据库:每天获取所有记录

pkln4tw6  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(184)

我已经尝试了所有的解决方案,我可以找到在这里,但我仍然来了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)
zzwlnbp8

zzwlnbp81#

Momentjs在add操作时会改变原始对象,但不会创建新对象。
因此需要克隆对象;否则,您将向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()
  },
});
nkhmeac6

nkhmeac62#

尝试使用toISOString()化日期:

const cdrIns = await CDRIn.find({
  createdAt: {
    $gte: today.toISOString(),
    $lt: today.add(1, 'day').toISOString(),
  },
});

相关问题