Compare date range in mongoDB using Typescript/Node

616 views Asked by At

I am trying to build a mongo query that is querying a DB collection which involves comparing an input date to be $lt and $gt the date stored in DB.

My current code looks like this which returns a query string.

    private createXYZ({
       ...inputs
    }: Type): Filter<Type> {
        const fromDate = new Date(`${input.creationDateFrom}`);
        const toDate = new Date(`${input.creationDateTo}`);
        return {
            'editedAt': {
                $gt: fromDate,
                $lt: toDate,
            },
        }
    }
}

Now here I am comparing editedAt to be between fromDate and toDate. When I try to console the query string with some dynamic date the editedAt section prints as below but I don't get any data out of it.

'editedAt': { '$gt': 2009-03-21T00:00:00.000Z, '$lt': 2024-03-29T00:00:00.000Z }

The query returns the result in Robo3T(MongoDB client) when date is compared like below:

db.getCollection('documents').find({
  'editedAt': {
    '$gt': ISODate("2009-03-21T00:00:00.000Z"),
    '$lt': ISODate("2024-03-29T00:00:00.000Z"),
  },
})

I am not sure as to how I can use this ISODate mongoDB native method in nodejs code so that it returns the results as expected. https://www.npmjs.com/package/mongodb

Can somebody help me here!

0

There are 0 answers