如何在Mongoose中查询日期之间的日期

问题描述 投票:0回答:1

我的 Mongo 数据库中有一组记录。

2023-09-12T00:10:17.558+00:00
2023-09-12T00:10:45.515+00:00
2023-09-12T00:10:49.121+00:00
2023-09-12T00:12:59.252+00:00
2023-09-12T23:23:45.238+00:00
2023-09-12T23:23:46.170+00:00
2023-09-12T23:34:43.082+00:00
2023-09-13T06:40:37.457+00:00

我正在使用 Mongoose find 来查询它

const findActivityLogsByFilter = async (filter: TEmployeeFilter, currentUser: IEmployeeAttributes) => {
  try {
    console.log(filter.startDate, filter.endDate);
    return await employee_activity_logsModel
      .find({
        employeeId: filter.employeeId,
        activity: { $in: filter.actions },
        logDate: { $gte: filter.startDate, $lte: filter.endDate },
        _discontinuedUser: null,
      })
      .sort({ _id: 'desc' })
      .exec();
  } catch (error) {
    throw new InternalServerError(messages.generalMessage.Error);
  }
};

如果我将

employeeId
activity
单独留在过滤器中,则会显示所有记录。但是当我放入
logDate
过滤器时。没有结果显示

我尝试了不同的日期格式,例如

fromDate: 2023-09-12, toDate: 2023-09-12
fromDate: Tue Sep 12 2023 16:04:46 GMT+0800 (Taipei Standard Time),
toDate: Tue Sep 12 2023 16:04:46 GMT+0800 (Taipei Standard Time)

甚至使用

moment
来格式化要在
from
to
日期过滤器上使用的日期,但没有显示结果。

我也尝试直接在 MongoDB Compass 上查询,但没有成功。

{
  employeeId:ObjectId('64f9731b4f8f4f269a44e7af'), 
  logDate:{
    $gte:ISODate('2023-09-12'),
    $lte:ISODate('2023-09-12')
  }
}

是否需要使用某种日期格式来查询日期(无论时间如何)?我期望的是获取日期为 2023-09-12 的所有记录,因为我的查询是

fromDate: 2023-09-12, toDate: 2023-09-12

javascript node.js mongodb mongoose date-range
1个回答
2
投票

当您使用

startDate: new Date("2023-09-12")
endDate: new Date("2023-09-12")
查询日期来过滤文档时:

logDate: { $gte: startDate, $lte: endDate }

查询将使用

logDate
过滤“2023-09-12T00:00:00Z”到“2023-09-12T00:00:00Z”内的文档。这只会匹配带有
logDate: "2023-09-12T00:00:00Z"
的文档。

您应该在

endDate
上添加 1 天并使用
$lt
:

filter.endDate.setDate(filter.endDate.getDate() + 1);
logDate: { $gte: filter.startDate, $lt: filter.endDate }

因此查询结果会变成

logDate: { $gte: new Date("2023-09-12"), $lt: new Date("2023-09-13") }

通过

logDate
获取文件的时间为“2023-09-12”。

© www.soinside.com 2019 - 2024. All rights reserved.