Compare MongoDB ISODate with string

Viewed 19

I'm currently working on a backend build with MERN and Typescript.

The problem comes when i try to compare Dates, which are are saved in Mongo as Date(ISODate(for example: "2022-09-14T16:00:00.000+00:00") and get compared to a string (for example: "2022-14-09").

I tried to convert the string with the Help of new Date(string) and compare then, but unfortunately it didn't work. I tried several Methods but they all don't work.

Do you have an idea?

data = await collections.events
          ?.find({
            location: params["place"],
            persons: { $gte: parseInt(params["persons"], 10) },
            time: { $gte: new Date(params["date"]) },
          })
          .toArray();
1 Answers

You can convert a Date to ISOString(), which corresponds to your MongoDB Date. Try not to use momentJs (deprecated), you can also just add 'T00:00:00.000Z' at the end of params["date"] (not the best practice)

new Date(params["date"]).toISOString()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

Btw I recommend you to do more verifications with your variables, like if you parseInt NaN, it will return undefined and your request can give you wrong results ;)

Related