Mongodb mongoose-根据本地日期自动检测本地时区和组数据

Mongodb mongoose-根据本地日期自动检测本地时区和组数据,mongodb,mongoose,Mongodb,Mongoose,我正在预算应用程序中执行日常开支功能。在数据库中,日期存储在UTC时区中。但是在响应中我希望它在用户的本地时区中按日期进行分组 // 'from' & 'to' are date start and end // '$date' and '$amount' are the keys in mongoDB model const aggregation = [ { $match: { date: { $gte: from, $l

我正在预算应用程序中执行日常开支功能。在数据库中,日期存储在UTC时区中。但是在
响应中
我希望它在用户的本地时区中按日期进行分组

// 'from' & 'to' are date start and end
// '$date' and '$amount' are the keys in mongoDB model 
const aggregation = [
        {
          $match: {
            date: { $gte: from, $lt: to }
          }
        },
        {
          $group: {
            _id: {
              $dateToString: {
                date: "$date",       // UTC
                format: "%m, %d, %Y" // Now it is grouped by date in UTC
              }
            },
            total: { $sum: "$amount" }
          }
        },
        {
          $sort: { _id: -1 }
        }
      ]
当前,响应数据如下所示:

[
  { _id: "08, 28, 2020", total: 50 },
  { _id: "08, 27, 2020", total: 100 },
  // ...
]
然而,问题是某些日期应该是前一天,但在UTC中错误地是明天的日期。正确的响应数据应为:

[
  { _id: "08, 28, 2020", total: 40 },
  { _id: "08, 27, 2020", total: 110 },
  // ...
]

// An expense of $10 was updated at 23pm on Aug 27 in user's timezone (e.g. New York) but stored in mongoDB as on Aug 28, which is UTC timezone.

如何根据自动检测到的用户时区在服务器端本地化日期?我可以在客户端执行此操作,但在这种情况下,将有更大的响应数据,因为我必须在响应数据中保留日期和时间,这是不可能仅按日期分组的。

我通过添加时区作为
$dateToString
选项来修复它,其中时区是客户端的参数:

$group: {
            _id: {
              $dateToString: {
                date: "$date",       // UTC
                format: "%m, %d, %Y", // Now it is grouped by date in UTC
                timezone: timezone
              }
            },
            total: { $sum: "$amount" }
          }

使用$bucket并使用UTC时间戳定义边界。@D.SM是的,我的问题是如何将UTC日期和时间自动转换为聚合中的本地日期和时间。时区偏移应根据用户位置自动检测。所有在线答案都针对固定时区,但我需要一个自动答案。MongoDB不支持时区,您需要在UTC中操作。或者,您可以预先计算日期,并将其存储为字符串或时区调整时间,然后按这些字段分组。