Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // aggregation wonts fetch any data if you pass strings instead of Date type
- // ref: https://stackoverflow.com/questions/47694008/aggregate-date-range-mongoose
- const now = new Date();
- const fourMonthAgo = new Date(now);
- fourMonthAgo.setMonth(fourMonthAgo.getMonth() - 4);
- console.log("now.toISOString()");
- console.log(now.toISOString());
- console.log("fourMonthAgo.toISOString()");
- console.log(fourMonthAgo.toISOString());
- /* wrong way
- console.log(
- (
- await PointsModel.aggregate([
- {
- $match: {
- $and: [
- { createdAt: { $lte: now.toISOString() } },
- { createdAt: { $gte: fourMonthAgo.toISOString() } },
- ],
- },
- },
- ])
- ).length
- );
- */
- // the right way, the following aggregations work perfectly
- console.log(
- (
- await PointsModel.aggregate([
- {
- $match: {
- $and: [
- {
- createdAt: {
- $lte: new Date(now.toISOString()),
- $gte: new Date(fourMonthAgo.toISOString()),
- },
- },
- ],
- },
- },
- ])
- ).length
- );
- console.log(
- (
- await PointsModel.aggregate([
- {
- $match: {
- $and: [
- { createdAt: { $lte: new Date(now.toISOString()) } },
- { createdAt: { $gte: new Date(fourMonthAgo.toISOString()) } },
- ],
- },
- },
- ])
- ).length
- );
- console.log(
- (
- await PointsModel.find({
- $and: [
- { createdAt: { $lte: now.toISOString() } },
- { createdAt: { $gte: fourMonthAgo.toISOString() } },
- ],
- })
- ).length
- );
- /* console output:
- now.toISOString()
- 2021-05-26T09:50:48.805Z
- fourMonthAgo.toISOString()
- 2021-01-26T10:50:48.805Z
- 0
- 25751
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement