Skip to content

fix: MongoDB aggregation pipeline with $dateSubtract from $$NOW returns no results #9822

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

mtrezza
Copy link
Member

@mtrezza mtrezza commented Jul 13, 2025

Pull Request

Issue

A MongoDB aggregation pipeline like this returns no results:

const pipeline = [
  {
    $match: {
      $expr: {
        $gte: [
          '$date',
          {
            $dateSubtract: {
              startDate: '$$NOW',
              unit: 'day',
              amount: 1,
            },
          },
        ],
      },
    },
  },
];

The reason is that Parse Server's aggregation pipeline parser only is able to handle simple date comparisons like:

const pipeline = [
  { 
    $match: {
      date: { $gte: '2025-07-11T00:00:00Z' },
  },
];

But it doesn't handle more complex expressions where the comparison is not a Date string or Date object, but another logical expression.

Approach

Adapt aggregation pipeline parser to handle complex expressions.

Tasks

  • Add tests

Copy link

parse-github-assistant bot commented Jul 13, 2025

🚀 Thanks for opening this pull request!

Copy link

coderabbitai bot commented Jul 13, 2025

📝 Walkthrough

Walkthrough

A new aggregation test was added to verify the use of the $dateSubtract operator with the $$NOW variable in MongoDB queries, specifically excluding Postgres. Additionally, the internal _convertToDate method in the Mongo storage adapter was updated to validate date strings before conversion, ensuring only valid dates are transformed.

Changes

File(s) Change Summary
spec/ParseQuery.Aggregate.spec.js Added a test for aggregation pipeline using $dateSubtract with $$NOW, excluding Postgres.
src/Adapters/Storage/Mongo/MongoStorageAdapter.js Improved _convertToDate to validate date strings before conversion; updated method comment to JSDoc style.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite as Parse.Query Aggregate Test
    participant DB as MongoDB Adapter

    TestSuite->>DB: Create two TestObject instances with different dates
    TestSuite->>DB: Execute aggregation pipeline with $dateSubtract from $$NOW
    DB-->>TestSuite: Return objects matching date >= $$NOW - 2 days
    TestSuite->>TestSuite: Assert only 1 result (date 1 day ago)
Loading
sequenceDiagram
    participant Adapter as MongoStorageAdapter
    participant Input as InputData

    Input->>Adapter: Call _convertToDate(data)
    Adapter->>Adapter: Check if string is a valid date
    alt Valid date string
        Adapter->>Input: Convert to Date object
    else Invalid date string
        Adapter->>Input: Return original string
    end
Loading

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn EBADENGINE Unsupported engine {
npm warn EBADENGINE package: '[email protected]',
npm warn EBADENGINE required: { node: '18 || 19 || 20 || 22' },
npm warn EBADENGINE current: { node: 'v24.3.0', npm: '11.4.2' }
npm warn EBADENGINE }
npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-13T00_35_56_192Z-debug-0.log


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@parseplatformorg
Copy link
Contributor

🎉 Snyk checks have passed. No issues have been found so far.

security/snyk check is complete. No issues have been found. (View Details)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
spec/ParseQuery.Aggregate.spec.js (1)

442-470: Excellent test for the $dateSubtract fix!

This test effectively verifies that MongoDB aggregation pipelines with $dateSubtract from $$NOW return correct results. The test setup and assertions properly validate the fix.

However, there's a comment error that should be corrected:

-    const obj2 = new TestObject({ date: new Date(new Date().getTime() - 2 * 24 * 60 * 60 * 1_000) }); // 3 days ago
+    const obj2 = new TestObject({ date: new Date(new Date().getTime() - 2 * 24 * 60 * 60 * 1_000) }); // 2 days ago
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3f5ae0 and 57fa546.

📒 Files selected for processing (2)
  • spec/ParseQuery.Aggregate.spec.js (1 hunks)
  • src/Adapters/Storage/Mongo/MongoStorageAdapter.js (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
spec/ParseQuery.Aggregate.spec.js (4)
Learnt from: RahulLanjewar93
PR: parse-community/parse-server#9744
File: spec/ParseLiveQuery.spec.js:0-0
Timestamp: 2025-04-30T19:31:35.344Z
Learning: In the Parse Server codebase, the functions in QueryTools.js are typically tested through end-to-end behavior tests rather than direct unit tests, even though the functions are exported from the module.
Learnt from: mtrezza
PR: parse-community/parse-server#9445
File: spec/ParseLiveQuery.spec.js:1312-1338
Timestamp: 2025-05-04T20:41:05.147Z
Learning: New tests in the parse-server repository should use async/await with promise-based patterns rather than callback patterns with `done()`.
Learnt from: mtrezza
PR: parse-community/parse-server#9445
File: spec/ParseLiveQuery.spec.js:1340-1375
Timestamp: 2025-05-09T09:59:06.289Z
Learning: New tests in the parse-server repository should use async/await with promise-based patterns rather than callback patterns with `done()`. The preferred pattern is to create a Promise that resolves when an expected event occurs, then await that Promise.
Learnt from: mtrezza
PR: parse-community/parse-server#9445
File: spec/ParseLiveQuery.spec.js:1340-1375
Timestamp: 2025-05-09T09:59:06.289Z
Learning: Tests in the parse-server repository should use promise-based approaches rather than callback patterns with `done()`. Use a pattern where a Promise is created that resolves when the event occurs, then await that promise.
🪛 Biome (1.9.4)
src/Adapters/Storage/Mongo/MongoStorageAdapter.js

[error] 970-970: Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.

TypeScript only syntax

(parse)


[error] 970-970: return type annotation are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax.

TypeScript only syntax

(parse)


[error] 971-984: This code is unreachable

(lint/correctness/noUnreachable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (12)
  • GitHub Check: PostgreSQL 15, PostGIS 3.3
  • GitHub Check: PostgreSQL 15, PostGIS 3.4
  • GitHub Check: PostgreSQL 16, PostGIS 3.5
  • GitHub Check: PostgreSQL 17, PostGIS 3.5
  • GitHub Check: Docker Build
  • GitHub Check: PostgreSQL 15, PostGIS 3.5
  • GitHub Check: Node 18
  • GitHub Check: MongoDB 6, ReplicaSet
  • GitHub Check: MongoDB 8, ReplicaSet
  • GitHub Check: Redis Cache
  • GitHub Check: MongoDB 7, ReplicaSet
  • GitHub Check: Node 20
🔇 Additional comments (3)
src/Adapters/Storage/Mongo/MongoStorageAdapter.js (3)

963-969: Good documentation improvement!

The JSDoc comment clearly explains the method's purpose and recursive behavior for handling aggregation pipeline objects.


975-975: Excellent validation improvement!

Using Date.parse() to validate date strings before conversion prevents invalid date strings from being converted to Date objects, which addresses the core issue with $dateSubtract operations.


977-984: Good recursive object handling.

The recursive processing of objects ensures that nested date values in aggregation pipelines are properly converted, which is essential for complex pipeline operations.

Copy link

codecov bot commented Jul 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 93.01%. Comparing base (c58b2eb) to head (57fa546).
Report is 9 commits behind head on alpha.

Additional details and impacted files
@@           Coverage Diff           @@
##            alpha    #9822   +/-   ##
=======================================
  Coverage   93.01%   93.01%           
=======================================
  Files         187      187           
  Lines       15094    15096    +2     
  Branches      174      174           
=======================================
+ Hits        14039    14041    +2     
  Misses       1043     1043           
  Partials       12       12           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mtrezza mtrezza merged commit 847a274 into parse-community:alpha Jul 13, 2025
23 of 25 checks passed
parseplatformorg pushed a commit that referenced this pull request Jul 13, 2025
## [8.2.3-alpha.1](8.2.2...8.2.3-alpha.1) (2025-07-13)

### Bug Fixes

* MongoDB aggregation pipeline with `$dateSubtract` from `$$NOW` returns no results ([#9822](#9822)) ([847a274](847a274))
@parseplatformorg
Copy link
Contributor

🎉 This change has been released in version 8.2.3-alpha.1

@parseplatformorg parseplatformorg added the state:released-alpha Released as alpha version label Jul 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
state:released-alpha Released as alpha version
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants