How can I query objects from the past 7 days with Parse JS SDK?

Viewed 1102

I am trying to fill a chart of data, the chart takes a number of orders each day of the past 7 days.

How can I query and group the past 7 days?

Sorry if its a bit complicated to understand.

2 Answers

You use the relativeTime operator which makes it very easy:

const query = new Parse.Query('Order');
query.greaterThan('createdAt', { $relativeTime: '7 days ago' });
const results = await query.find();

This operator is badly documented but was introduced a while ago and is fully tested.

You can either use the 'n days ago' or 'in n days'

You can also see the test suite here:

https://github.com/parse-community/parse-server/blob/master/spec/ParseQuery.spec.js#L4155

Get the date which is 7 days ago:

let d = new Date();
d.setDate(d.getDate()-7);

Form a greaterThan query using that date:

let query = new Parse.Query("Order");
query.greaterThan('createdAt', d);
query.find.then(function(results) {
    // results will be instances of Order created starting 7 days ago
    // underscore _.groupBy() is useful for grouping
});

Notes:

  • Change the name of the object from "Order" to whatever your order object is named.
  • Change createdAt to any valid date property on the Order object or leave it as-is if you're going for creation date
  • This answer gives objects created starting 7 days before the invocation. Sometimes business apps want to measure calendar days. Get that by zeroing out the hours, mins, seconds of d
Related