TheMean Won
TheMean Won

Reputation: 69

Waterline query for records created within the last 7 days?

Sails v12.14 connecting to MongoDB with Waterline

Is there a way to do a find query for all records created within the last 7 days from the current date? I've tried searching for an answer, but I'm guessing I'm not hitting the right keywords to come up with the answer I need.

For example, here's my function:

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);
   });
}

This works fine for pulling all tickets, but I'm not sure how to filter for only the last 7 days.

Upvotes: 0

Views: 176

Answers (2)

khalil
khalil

Reputation: 741

This will retrieve tickets with open_date greater than 24h * 7days (168 hours)

 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);
        });
    }

Upvotes: 0

khushalbokadey
khushalbokadey

Reputation: 1152

I have used momentJS for date formatting. Following code snippet should work.

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);
    });
}

Upvotes: 1

Related Questions