Mongo date query helper for common queries
Builds query objects for commonly used mongo date queries. Helpful in generating data for tables, graphs, and charts.
Works with both mongoose and mongodb. All dates are in UTC.
$ npm install mongo-date-query
import mdq from "mongo-date-query";
const mdq = require("mongo-date-query");
import mdq from "mongo-date-query";
//mongoose
User.find({ createdAt: mdq.lastWeek() }, function (err, users) {
if (!err) {
console.log(users);
}
});
//mongodb
const collection = db.collection("users");
collection.find({ createdAt: mdq.yesterday() }).toArray(function (err, users) {
if (!err) {
console.log(users);
}
});
General pattern:
-
this: Start and end of a time unit [thisHour(), thisYear() etc.]
-
next: From now [nextMonth() = month from now]
-
last: Before now [lastYear() = year before now]
-
coming: The current given unit is not included [comingYear() = year after (not including) this year]
-
previous: The current given unit is not included [previousMonth() = month before (not including) this month]
-
before: Before the given unit [beforePreviousMonth(), beforeLastMinute()]
-
after: After the given unit [afterThisWeek(), afterNextMonth(), afterComingYear()]
-
lastToNext: From last time unit to next [lastToNextMinute() = from last minute to next minute, lastToNextDay() = from last 24 hours to next 24 hours]
-
APIs with plural version: Takes a Number parameter. Default is 1. [nextMonths(2), comingYears(3), lastWeeks(4), beforePreviousMonths(3), afterComingYears(5) lastToNextDays(3, 4)]
MIT © Talha Awan