首页 > 解决方案 > 获取 24 小时前的 X 条记录 Mongoose

问题描述

我的项目基于 Hapi.js 和 Mongoose。我被困在 24 小时前的 X 价格中。

我以这种方式获得最新添加的记录:

        const pricesnow = await Prices.find({
          currency_id: {
            $in:
              currencies[k].id
          },
          createdAt: {
            $gt: new Date().getTime() - 1000 * 60 * 1
          }
        })

所以我认为我可以使用以下代码从 24 小时前获取 x 记录:

        const prices24h = await Prices.find({
          currency_id: {
            $in:
              currencies[k].id
          },
          createdAt: {
            $gt: new Date().getTime() - 86400000,
            $lt: new Date().getTime() - 86399999
          }
        })

但是即使数据库中有数据,24小时前的价格也不会返回。

第二个代码仅在时间跨度在一小时内有效。

之后,我将从 pricenow 中减去 price24h 以计算 24h 百分比。

提前感谢您的回答。

标签: node.jsdatabasemongodbmongoosehapijs

解决方案


您可以使用limitsort功能find

const pricesnow = await Prices.find({
  currency_id: {
    $in: [], // replace with currency array
  },
  createdAt: { $gt: new Date(Date.now() - 86400000) },
})
  .sort({ createdAt: -1 })
  .limit(10);


推荐阅读