0

I'm making a request from Angular to a MongoDB table (accessed through RESTHeart) where each record contains a "startDate" field. When I fetch some records I get this date as an object:

startDate: {$date: 1609718400000}

I want to filter only future dates, however this filter query doesn't work as expected:

`{ "startDate": { $gt: { $date: ${Date.now()} } } }`

I'm still getting past dates. What am I doing wrong?

Edit: Here's my angular function:

getTerms(url: string): Observable<TermDto[]> {
    const params = createParams()
        .append('filter', `{ "startDate": { $gt: { $date: ${Date.now()} } } }`);
    
    return this.client.get<TermDto[]>(url, {params})
}
koswag
  • 83
  • 1
  • 1
  • 7

4 Answers4

1

RESTHeart uses the Extended JSON representation of MongoDB.

Dates are represented as {"$date": {"$numberLong": "<millis>"}}

Where < millis > is the epoch time in milliseconds.

So the correct filter is:

?filter={ "startDate": { "$gt": {"$date":  {"$numberLong": "1613381427"} } }
Andrea Di Cesare
  • 1,125
  • 6
  • 11
1

The simplest way that worked for me was this:

{ startDate: { $gt: new Date() } }

My problem derived from using an aggregation - when I passed additional "avars" query parameter:

...?avars={'id': "some-id"}&filter={'startDate': {$gt: new Date()}}

It somehow ignored the "filter" parameter. It would be great if someone was able explain why it happens.

My final solution for aggregation was validating date on frontend.

koswag
  • 83
  • 1
  • 1
  • 7
0

MongoDb use ISO format, try replacing Date.now() with new Date().toISOString()

Munzer
  • 2,216
  • 2
  • 18
  • 25
  • Now I'm getting a 400 error with the following message: `"illegal filter paramenter: { 'startDate': { $gt: 2021-02-12T16:04:14.456Z } }"` – koswag Feb 12 '21 at 16:05
  • Wrap it with quotes – Munzer Feb 12 '21 at 16:14
  • Tried that - there is no error, but past dates are still not filtered. The query looks like this: `"{ startDate: { $gt: "2021-02-12T16:17:10.078Z" } }"` – koswag Feb 12 '21 at 16:18
0

This should work:

{ startDate: { $gt: new Date(Date.now()) } }
  • Nope, still getting 400: `"illegal filter paramenter: { startDate: { $gt: new Date(Date.now()) } }"` – koswag Feb 12 '21 at 17:18