【问题标题】:Waterline query for records created within the last 7 days?过去 7 天内创建的记录的水线查询?
【发布时间】:2018-08-31 15:06:29
【问题描述】:

Sails v12.14 使用 Waterline 连接到 MongoDB

有没有办法对从当前日期起最近 7 天内创建的所有记录进行查找查询?我尝试过寻找答案,但我猜我没有找到正确的关键字来找到我需要的答案。

例如,这是我的函数:

getOpen: function getOpen(req, res) {
 Ticket.find({
  status: "open",
  open_date: [insert magic here]
 }).then(function response(findModelResults) {
    res.json(200, findModelResults);
   })
   .catch(function error(findModelError) {
    sails.log.error('TicketController.getOpen', findModelError);
    res.json(500, findModelError);
   });
}

这适用于提取所有票证,但我不确定如何仅过滤过去 7 天。

【问题讨论】:

    标签: javascript sails.js waterline sails-mongo


    【解决方案1】:

    我使用momentJS 进行日期格式化。以下代码 sn-p 应该可以工作。

    getOpen: function getOpen(req, res) {
      const date = new Date();
      Ticket.find({
          status: "open",
          open_date: {
            '>=': moment(new Date(date.getFullYear(), date.getMonth(), date.getDate() - 7))
              .utc()
              .toISOString();
          }
        })
        .then(function response(findModelResults) {
          res.json(200, findModelResults);
        })
        .catch(function error(findModelError) {
          sails.log.error('TicketController.getOpen', findModelError);
          res.json(500, findModelError);
        });
    }
    

    【讨论】:

    • 我已经在我的应用程序中使用 momentJS 来完成其他一些任务,所以这是一个简单的实现。谢谢。
    【解决方案2】:

    这将检索 open_date 大于 24h * 7days(168 小时)的票

     getOpen: function getOpen(req, res) {
          var sevenDaysAgo = new Date();
          sevenDaysAgo.setTime(new Date().getTime() - (7 * 24 * 3600 * 1000));
          Ticket.find({
              status: "open",
              open_date: {
                '>=': sevenDaysAgo
              }
            })
            .then(function response(findModelResults) {
              res.json(200, findModelResults);
            })
            .catch(function error(findModelError) {
              sails.log.error('TicketController.getOpen', findModelError);
              res.json(500, findModelError);
            });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-20
      • 2013-07-08
      • 2020-03-26
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      相关资源
      最近更新 更多