Mongoose.countDocuments在按时刻计算去年创建的js文档时无法工作

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

我正在开发一个名为wertik-js的开源库,它使用Graphql,我已经添加了报告类型的助手,根据创建的时间返回mongoose模型的计数。在这个案例中,我有这样的报表:total_count,total_added_last_year等,total_added_today等,对于今天,我用这种方式进行了过滤。

model.countDocuments(
  {
    created_at: {
      $gt: moment().startOf("day"),
      $lt: moment().endOf("day"),
    },
  },
  function (err, count) {
    resolve(count);
  }
);

而且效果很好 当使用去年,我有去年创建的数据。去年的数据是这样计算的

model.countDocuments(
  {
    created_at: {
      $gt: moment().subtract(1, "year").startOf("year"),
      $lt: moment().subtract(1, "year").endOf("year"),
    },
  },
  function (err, count) {
    resolve(count);
  }
);

但去年的计数不能用,每次都返回0,但我确定我写的查询方式是正确的,但它返回的是错误的数字,即0,其中total_added_today返回正常。

要重现这个bug,你可以把这个分支拉出来 https:/github.comUconnect-Technologieswertik-jstree188-graphql-or-rest-api-enpoint-to-showall-stats。 和。

  1. 安装软件包并运行服务器 sudo yarn && sudo yarn dev
  2. 前往 http:/localhost:4000
  3. 并执行graphql查询。
{
  roleStats {
    total_count
    total_added_this_month
    total_added_this_week
    total_added_last_7_days
    total_added_today
    total_added_last_month
    total_added_last_90_days
    total_added_last_year
    total_added_this_year
  }
}

你就能重现这个错误。

你可以检查这个文件 https:/github.comUconnect-Technologieswertik-jsblob188-graphql-or-rest-api-enpoint-to-show-all-statssrcframeworkreportingindex.ts#L110。 从第110行开始,Mongoose开始。

我在这里做错了什么?

任何帮助都将被视为对这个开源项目的贡献。

编辑

我正在搜索的一个示例文档。

{
    "_id": {
        "$oid": "5ed85b8893280c021c2ddfd6"
    },
    "name": "John",
    "created_at": "Thu Jun 04 2019 07:25:12 GMT+0500 (Pakistan Standard Time)",
    "updated_at": "Thu Jun 04 2019 07:25:12 GMT+0500 (Pakistan Standard Time)",
    "__v": 0
}
node.js mongodb mongoose graphql apollo
1个回答
1
投票

问题是 created_at 文档中的字段包含一个字符串。"Thu Jun 04 2019 07:25:12 GMT+0500 (Pakistan Standard Time)"

这不能按日期时间排序,也不能用任何日期范围运算符匹配。

你可以尝试用聚合或更新将这些转换为日期。

db.collection.update({created_at: {$type: "string"}},
                     [{$set: {created_at: {$toDate: {"$created_at"}}],
                     {multi:true})

然后你就可以执行 $gt$lt 检验的意义。


0
投票

我认为问题出在这一行

 $lt: moment().subtract(1, "year").endOf("year"),

应该是

      $lt: moment().endOf("year"),
© www.soinside.com 2019 - 2024. All rights reserved.