Advertisement
nodejsdeveloperskh

aggregate not working but find works.

May 26th, 2021 (edited)
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // aggregation wonts fetch any data if you pass strings instead of Date type
  2. // ref: https://stackoverflow.com/questions/47694008/aggregate-date-range-mongoose
  3. const now = new Date();
  4. const fourMonthAgo = new Date(now);
  5. fourMonthAgo.setMonth(fourMonthAgo.getMonth() - 4);
  6. console.log("now.toISOString()");
  7. console.log(now.toISOString());
  8. console.log("fourMonthAgo.toISOString()");
  9. console.log(fourMonthAgo.toISOString());
  10. /* wrong way
  11. console.log(
  12.   (
  13.     await PointsModel.aggregate([
  14.       {
  15.         $match: {
  16.           $and: [
  17.             { createdAt: { $lte: now.toISOString() } },
  18.             { createdAt: { $gte: fourMonthAgo.toISOString() } },
  19.           ],
  20.         },
  21.       },
  22.     ])
  23.   ).length
  24. );
  25. */
  26. // the right way, the following aggregations work perfectly
  27.     console.log(
  28.       (
  29.         await PointsModel.aggregate([
  30.           {
  31.             $match: {
  32.               $and: [
  33.                 {
  34.                   createdAt: {
  35.                     $lte: new Date(now.toISOString()),
  36.                     $gte: new Date(fourMonthAgo.toISOString()),
  37.                   },
  38.                 },
  39.               ],
  40.             },
  41.           },
  42.         ])
  43.       ).length
  44.     );
  45.     console.log(
  46.       (
  47.         await PointsModel.aggregate([
  48.           {
  49.             $match: {
  50.               $and: [
  51.                 { createdAt: { $lte: new Date(now.toISOString()) } },
  52.                 { createdAt: { $gte: new Date(fourMonthAgo.toISOString()) } },
  53.               ],
  54.             },
  55.           },
  56.         ])
  57.       ).length
  58.     );
  59. console.log(
  60.   (
  61.     await PointsModel.find({
  62.       $and: [
  63.         { createdAt: { $lte: now.toISOString() } },
  64.         { createdAt: { $gte: fourMonthAgo.toISOString() } },
  65.       ],
  66.     })
  67.   ).length
  68. );
  69.  
  70. /* console output:
  71. now.toISOString()
  72. 2021-05-26T09:50:48.805Z
  73. fourMonthAgo.toISOString()
  74. 2021-01-26T10:50:48.805Z
  75. 0
  76. 25751
  77. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement