mhlavacka
mhlavacka

Reputation: 701

MongoDB, Node: Query ISODate fields with a query not build directly in find operation

I am using nodejs with the official mongodb driver.

I have documents with a date property stored as ISODate type.

The query is built beforehand and stored as a string ex. '{createdAt: {$gte: "FROM_DATE", $lte: "TO_DATE"}}' and passed onto server together with variables for fromDate and toDate.

There the query is parsed using json5 and "FROM_DATE" is replaced by new Date(fromDate) and same for the other.

The problem is new Date(fromDate) is always stored as string and I end up with the query below:

{createdAt: {
  $gte: 'Tue Mar 10 2020 22:23:51 GMT+0100 (Central European Standard Time)',
  $lte: 'Thu Apr 09 2020 22:23:51 GMT+0200 (Central European Summer Time)'
}}

Which as string it won't query ISODate format.

Is it just because I'm replacing string it gets returned as string by default or where is the issue? Thanks.

Upvotes: 0

Views: 83

Answers (2)

mhlavacka
mhlavacka

Reputation: 701

I figured out the problem. The function .replace() always replaces string, with a string result.

I found the solution to avoid .replace() here if anyone has the same problem - https://stackoverflow.com/a/40436561/4693613.

Upvotes: 0

Rachit Anand
Rachit Anand

Reputation: 674

You can use the toISOString function while creating a date, as shown below

const date = new Date('01-JAN-2020');
console.log(date)
//Wed Jan 01 2020 00:00:00 GMT-0600 (Central Standard Time)

const newDate = new Date('01-JAN-2020').toISOString();
console.log(newDate)
//2020-01-01T06:00:00.000Z

Upvotes: 1

Related Questions